BJ_Covert_Action has asked for the wisdom of the Perl Monks concerning the following question:
So I've been bejiggering with this code for awhile and it's not working out the way I need it to. I am parsing a text file where the first line consists of headings that I would like to use for keys in a hash. The next few lines contain values. I'd like to store each line of values in a hash that is keyed by the headings in the first line, and contains the values in the second line. However, I'd like to store each of those hashes in a master hash that is keyed by the first value in each row. So the data I am looking at resembles the following:
Heading 1 Heading 2 Heading 3 ... Value A1 Value A2 Value A3 ... Value B1 Value B2 Value B3 ... . . .
I am trying to parse that code with the following subroutine (please note values are delimited by tabs, so the parsing is working as expected)
sub get_fields{ my $local_filein = shift; # Input file needs to be the first fi +le passed to get_fields my %tmp_hash; my %tickets; my @keys; my @values; while(my $line = <$local_filein>){ chomp $line; if ($line =~ m/^\D/){ @keys = split(/\t/, $line); }elsif($line =~ m/d/){ @values = split(/\t/, $line); @tmp_hash{@keys} = @values; # foreach(keys %tmp_hash){ # print "KEY: $_ VALUE: $tmp_hash{$_}\n" # } $tickets { $values[0] } = %tmp_hash; #$tickets{ @values[0]{@keys}} = @values; #$tickets{ $values[0] } = { each %tmp_hash }; # Each is a + piece of shit. Use @ context or something else. } } #@tickets{@keys} = @values; return %tickets; }
The line of code I am having trouble with is the one where I am trying to assign the values of %tmp_hash into the master hash %tickets. As you can see, I've tried a few different things which I've commented out. Basically, %tmp_hash is getting created just fine by assigning it the arrays @keys and @values. But I'd like to do something similar to make %tickets the hash of temporary hashes keyed by the first value in the @values array. I can't seem to get the context to work out.
Any help y'all could provide would be appreciated.
Thanks!
Brady
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Storing a Hash Made of Two Arrays in Another Hash
by tobyink (Canon) on Jan 10, 2012 at 18:01 UTC | |
by BJ_Covert_Action (Beadle) on Jan 10, 2012 at 18:51 UTC | |
by BJ_Covert_Action (Beadle) on Jan 10, 2012 at 18:10 UTC | |
|
Re: Storing a Hash Made of Two Arrays in Another Hash
by toolic (Bishop) on Jan 10, 2012 at 17:59 UTC | |
by BJ_Covert_Action (Beadle) on Jan 10, 2012 at 18:07 UTC |