如何使用foreach读取哈希的元素?

时间:2010-06-30 07:58:51

标签: perl hash

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;
}

它没有以我期望的方式显示。

3 个答案:

答案 0 :(得分:2)

第一行末尾缺少逗号。

%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;
}

答案 1 :(得分:1)

你可以试试这个:

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};
        }
    }
}

答案 2 :(得分:0)

<强>也许

#/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();

<强>输出:

$VAR1 = [
          'testvalue',
          10
        ]; 
$VAR1 = [
          'testvalue',
          20
        ]; 
$VAR1 = [
          'testvalue',
          30
        ]; 
$VAR1 = [
          'testvalue',
          40
        ];