How do I read elements of a hash using foreach?
use Data:开发者_高级运维:Dumper;
%hash = (
Key => {test => [[testvalue, 10], [testvalue, 20]]},
Key2 => {test => [[testvalue, 30], [testvalue, 40]]},
);
my $parm = $hash{Key}{test};
foreach my $test_p (@{$parm}) {
print Dumper $test_p;
}
It is not displaying in the way I expect.
A comma is missing at the end of the first line.
%hash = (
Key => {
test => [
[ testvalue , 10 ],
[ testvalue , 20 ]
]
},
Key2 => {
test => [
[ testvalue , 30 ],
[ testvalue , 40 ]
]
}
);
my $parm = $hash{Key}{test} ;
foreach my $test_p (@$parm) {
use Data::Dumper;
print Dumper $test_p;
}
You can try this:
my %hash = (
Key => {test => [['testvalue', 10], ['testvalue', 20]]},
Key2 => {test => [['testvalue', 30], ['testvalue', 40]]},
);
my $parm = $hash{Key}{test};
foreach my $test_p (@{$parm}) {
print Dumper $test_p;
}
foreach my $test (keys %hash) {
my $test1 = $hash{$test};
print Dumper $test;
foreach my $test2 (keys %{$test1}) {
print Dumper $test2;
my $test3 = $hash{$test}{$test2};
foreach my $test_p (@{$test3}) {
print Dumper @{$test_p};
}
}
}
Perhaps:
#/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
sub main{
my %hash = ( Key => { test => [[ "testvalue" , 10 ], [ "testvalue" ,20]] },
Key2 => { test => [[ "testvalue" , 30 ], [ "testvalue" ,40]] } );
foreach my $key (sort keys %hash){
my $parm = $hash{$key}{test};
print Dumper $_ foreach(@$parm);
}
}
main();
Outputs:
$VAR1 = [
'testvalue',
10
];
$VAR1 = [
'testvalue',
20
];
$VAR1 = [
'testvalue',
30
];
$VAR1 = [
'testvalue',
40
];
精彩评论