secondly, I'd be inclined to re-jig your hash format a bit. Your example shows a hash of a hash, containing values which are array references with hashes in them?. Seems a bit overboard, you could get away with just a hash of a hashes containing array refences, but I'd put the array reference in its own named key, just for flexibilty. for example
ignoring your code and just taking your data, I'd attack this by processing the rows in order, keeping track of the current mode and component, and, when I found a command, sticking it straight into the hash. something like this...you show $hash{'mode'}{'component'} = [{'command' => 'cmd1'}, {'command' => 'cm +d2'}]; simplist would be $hash{'mode'}{'component'} = ['cmd1', 'cmd2']; but I'd go for $hash{'mode'}{'component'}{'commands'} = ['cmd1', 'cmd2'];
the tricksy part of that is the line...#!/perl -w use Data::Dumper; use strict; my %hash; my $current_comp = ""; my $current_mode = ""; my %the_hash; while (<DATA>) { chomp; my ($coord,$data) = split /=>/; my ($row,$col) = split /,/, $coord; if ($col == 0) { $current_comp = $data; next; } if ($col == 2) { $current_mode = $data; next; } if ($col == 4) { push @{$the_hash{$current_mode}{$current_comp}{'commands'}}, $ +data; next; } } print Dumper(\%the_hash);
.. which makes perl do all sorts of things for us. Just the fact that we're referencing the hash key "$the_hash{$current_mode}{$current_comp}{'commands'}" makes perl auto-vivify it, then the whole thing is wrapped up as an array refence, Perl again is very obliging, assumes we know what were doing and creates us a hash reference for us which we can then push to.push @{$the_hash{$current_mode}{$current_comp}{'commands'}}, $data;
The output should end up looking something like this
HTH, Rob$VAR1 = { 'mode1' => { 'comp3' => { 'commands' => [ 'command1', 'command2' ] }, 'comp1' => { 'commands' => [ 'command1' ] } }, 'mode2' => { 'comp2' => { 'commands' => [ 'command1', 'command2', '' ] } } };
In reply to Re: how to build the hash for below code
by reasonablekeith
in thread How Do I Populate a Hash of Hashes?
by srins
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |