Bilco105
07-07-2008, 12:16 PM
Hi,
I currently have the following multi-level hash array defined..;
%CFG = (
'blah' => '',
'blah' => '',
'2ndlevel' => {
'BLAH1' => {
'DA' => ,
},
'BLAH1' => {
'DA' => ,
}
},
);
which I access using a package, $BLAH::$BLAH{'blah'}
How would I loop through the second level array, and perform actions on each entry (i.e. BLAH1, BLAH2?)
Examples would be appreciated.
Thanks
jasonaward
07-07-2008, 12:54 PM
Here's an example, let me know if that's not specific enough.
foreach $key1 ( keys %CFG ){
foreach $key2 ( keys %{$CFG{$key1}} ){
print "$key1,$key2," . $CFG{$key1}{$key2}{'DA'} . "\n";
}
}
Bilco105
07-07-2008, 07:11 PM
I just want to loop through the second level hash array, is that possible?
jasonaward
07-07-2008, 07:18 PM
What do you mean? Which values are you trying to access?
foobic
07-07-2008, 08:04 PM
You need to be careful because your main variable is a hash while the inner arrays are hashrefs. Things are a lot cleaner if you use all hashrefs and the -> syntax:
my $CFG = {
'blah' => '',
'blah' => '',
'secondlevel' => {
'BLAH1' => {
'DA' => 'hello world',
},
'BLAH2' => {
'DA' => ,
}
},
};
print $CFG->{secondlevel}->{BLAH1}->{DA},$/;
#This also comes in handy:
use Data::Dumper;
print Dumper($CFG);
Bilco105
07-08-2008, 03:29 AM
foobic,
If i do this, can I still loop through the secondlevel.
A good example would be, I want 'blah' as a normal variable using print $CFG->{blah}. But then later, I want to loop through the secondlevel elements and print there value.
So I would end up with
BLAH1's DA is 'hello world'
BLAH2's DA is ''
foobic
07-08-2008, 04:03 AM
You can't print a reference (well, you can, but it's not generally useful). Define a name for it as a string and you can print $CFG->{blah}->{name}.
Then I think you want something like this:
foreach my $key ( keys %{$CFG->{secondlevel}} ) {
print "$key\'s DA is ",$CFG->{secondlevel}->{$key}->{DA},$/;
}
Bilco105
07-08-2008, 05:19 AM
Thats it, perfect.
Thanks Chris! :)