Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 147
  • Last Modified:

I need help creating a hash. I am Stumped!

I need to create a hash by parsing the following information.  I would like my hash to look like this.

%Hashname (
            template:Actioncode => i
            SBID       => 100200401
            BusName    => Mikes System Test1
            City       => Douglas
            State      => MA
            Zip        => 01516
            Phone      => 5084742781
            CategoryID => 14438
);


This is the information that I would be parsing in the file.  The idea is to recreate the hash for each line below the template line.
I would greatly appreciate this.  One thing to note is that the script would have to be dynamic becuase the template line wont always look like that.  It could have extra fields.  Thank you!

template:Actioncode|SBID|BusName|City|State|Zip|Phone|CategoryID
i|100200401|Mikes System Test1|Douglas|MA|01516|5084742781|14438
i|100200402|Mikes System Test2|Douglas|MA|01516|5084742782|14438
i|100200403|Mikes System Test3|Douglas|MA|01516|5084742783|14438
i|100200404|Mikes System Test4|Douglas|MA|01516|5084742784|14438
i|100200405|Mikes System Test5|Douglas|MA|01516|5084742785|14438

Here's all i got now.

# open up the text file to parse.
open (IUD, "SomeTextfile.txt") or die "Can't open textfile: $!";
while (<IUD>)
{
   # create my hash

}
close IUD;


0
maddhacker24
Asked:
maddhacker24
1 Solution
 
TintinCommented:
#!/usr/bin/perl
use strict;

open IUD, "SomeTextfile.txt" or die "Can not open textfile: $!\n";

chomp ($_) = <IUD>;
my @fields = split(/\|/);
my %hash;

while (<IUD>) {
  chomp;
  my $i=0;
  foreach split(/\|/) {
    $hash{$fields[$i]} = $_;
    $i++;
  }
}

close IUD;

However, I'm sure someone will come up with a 1 line map solution.
0
 
holliCommented:
use Data::Dumper;
use strict;

open (IUD, "t.txt") or die "Can't open textfile: $!";

# split fields line
my $line = <IUD>; chomp ($line);
my @f = split (/\|/, $line);
my @data = ();
my %data = ();

while ($line = <IUD>)
{
  # split value line
  chomp ($line);
  my @v = split (/\|/, $line);

  # create my hash
  my %h = map { $f[$_], $v[$_] } (0..$#v);

  # build array of hashes
  push @data, \%h;

  # or hash of hashes with SBID as field
  $data{$f[1]} = \%f;

}

print Dumper (\@data);
close IUD;
0
 
maddhacker24Author Commented:
Thank you very much!
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now