robertwojnar robertwojnar - 3 months ago 10
Perl Question

Print multidimensional array in Perl, with keys

I have this kind of array in Perl:

my $foo_bar;

$foo_bar->{"foo"} //= [];
push @{$foo_bar->{"foo"}}, "foo1";
push @{$foo_bar->{"foo"}}, "foo2";
push @{$foo_bar->{"foo"}}, "foo3";

$foo_bar->{"bar"} //= [];
push @{$foo_bar->{"bar"}}, "bar1";
push @{$foo_bar->{"bar"}}, "bar2";
push @{$foo_bar->{"bar"}}, "bar3";


The result I'm trying to get is:


  • foo: foo1, foo2, foo3

  • bar: bar1, bar2, bar3



I have no idea.. I'm trying this:

foreach my $fb(@$foo_bar){

}


I'm getting an error:


Not an ARRAY reference at ./test.pl line 417, line 1000.

Answer

You need to iterate $foo_bar as a hash ref, not as an array ref. And because it's a hash, you need to get the keys first and then work with them.

use feature 'say';

#                 | you only iterate the keys ...
#                 |    | this percent is for hash  
#                 V    V     
foreach my $key ( keys %{ $foo_bar } ) {

    #    | ... and use the key here 
    #    |                   | this one is an array ref
    #    |                   |  | ... and the value here
    #    |                   |  |
    #    V                   V  VVVVVVVVVVVVVVVV
    say "$key ", join( ', ', @{ $foo_bar->{$key} } );
}

It helps to use Data::Dumper or Data::Printer to look at your data structure. This one is Data::Printer, which is good for human consumption.

 \ {                  # curly braces are hash refs
    bar   [           # square braces are array refs   
        [0] "bar1",
        [1] "bar2",
        [2] "bar3"
    ],
    foo   [
        [0] "foo1",
        [1] "foo2",
        [2] "foo3"
    ]
}
Comments