开发者

How do I read elements of a hash using foreach?

开发者 https://www.devze.com 2023-01-05 09:03 出处:网络
use Data:开发者_高级运维:Dumper; %hash = ( Key=> {test => [[testvalue, 10], [testvalue, 20]]},
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
        ];
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号