Perl hash dereferencing hashes

I am just learning perl.

I am trying to rewrite this layered loop using temporary variables so as not to require previous keys ( $key1 $key2) to access (dereference) up to $key3. What would be the easiest way to do this. Thank.

for my $key1 ( keys %foo )
{
    for my $key2 ( keys %{$foo{$key1}} )
    {
        for my $key3 ( keys %{$foo{$key1}{$key2}} )
+3
source share
4 answers

You can use whileand eachas follows:

while (my ($key1, $inner_hash) = each %foo) {

    while (my ($key2, $inner_inner_hash) = each %$inner_hash) {

        while (my ($key3, $value) = each %$inner_inner_hash) {
            print $value;
        }
    }
}

This approach uses less memory than foreach keys %hashthat, which builds a list of all hash keys before starting the iteration. The disadvantage eachis that you cannot specify the sort order. See more details.

+5
source

You are looking for something like this:

for my $key1 ( keys %foo )
{
    my $subhash = $foo{$key1};
    for my $key2 ( keys %$subhash )
    {
        my $subsubhash = $subhash->{$key2};
        for my $key3 ( keys %$subsubhash )
+4

:

foreach(values %foo){
  foreach(values %$_){
    foreach my $key3 (keys %$_){
      print $key3;
    }
  }
}
+2

perl.

. .

, ($ key1 $key2), () $key3. .

, , , - , - .

, %foo :

$foo{one}->{alpha}->{apple};
$foo{one}->{alpha}->{berry};
$foo{one}->{beta}->{cucumber};
$foo{one}->{beta}->{durian};
$foo{two}->{uno}->{eggplant};
$foo{two}->{uno}->{fig};
$foo{two}->{dos}->{guava};
$foo{two}->{dos}->{honeydew};

, -> , , -, . .

, . ?

-> . :

$foo{one}->{alpha};
$foo{one}->{beta};
$foo{two}->{uno};
$foo{two}->{dos};

, , , , . , , - , .

. , . , . , - , :

$foo{one};
$foo{two};

, , , . , , .

, - , , , .

- :

$person{$ssn}->{NAME}->{FIRST} = "Bob";
$person{$ssn}->{NAME}->{MI}    = "Q.";
$person{$ssn}->{NAME}->{LAST}  = "Smith";

Here I can go directly to the first, last and average initial value of each person. All I have to do is go through the various social security numbers:

for my $ssn ( sort keys %person ) {
    say "My name is " . $person{$ssn}->{NAME}->{FIRST}
       . " " . $person{$ssn}->{NAME}->{MI}
       . " " . $person{$ssn}->{NAME}->{LAST};
}
+1
source

All Articles