rjulich has asked for the wisdom of the Perl Monks concerning the following question:

I have 4 hash tables and I want to loop through array and then through each hash table.

Array of Hashes:

@array = (%hash0, %hash1, %hash2, %hash3); for($i = 0; $i < 4; $++) { foreach $key(key "%hash[$i]" or "$array[$i]") { print "$key\n"; } }

I know that %hash$i isn't the correct way to do this, but how do I do this? Let me know if I can provide any other information.

Replies are listed 'Best First'.
Re: Loop through array of hashes
by johngg (Canon) on Jan 21, 2016 at 18:11 UTC

    Your @array = (%hash0, %hash1, %hash2, %hash3); will just flatten the four hashes into one list. Do this:-

    my @array = ( \ %hash0, \ %hash1, \ %hash2, \ %hash3 );

    instead. Then to access them:-

    foreach my $hashref ( @array ) { print "$_\n" for keys %$hashref; }

    Note that I use my as there should be a use strict; (probably along with a use warnings;) at the top of the script.

    Cheers,

    JohnGG

Re: Loop through array of hashes
by hippo (Archbishop) on Jan 21, 2016 at 18:14 UTC
    # use hashrefs to avoid them being expanded into the list. @array = (\%hash0, \%hash1, \%hash2, \%hash3); # Loop over the array for my $href (@array) { for my $key (keys %$href) { print "key: $key, value: $href->{$key}\n"; } }
Re: Loop through array of hashes
by jeffa (Bishop) on Jan 21, 2016 at 18:51 UTC

    Why not use a function for that?

    use strict; use warnings; my %foo = ( one => 1, two => 2 ); my %bar = ( three => 3, four => 4 ); my %baz = ( five => 5, six => 6 ); dump_keys( $_ ) for \%foo, \%bar, \%baz; sub dump_keys { print "$_\n" for keys %{+shift} }

    Update: I am using ONE list without the need to wrap it in an array.

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    

      It's that classic blunder, less well known than getting involved in a land war in Asia: use of numbered variables instead of an array! Especially when the OP calls for it.

      use strict; use warnings; my @aoh; push @aoh, { one => 1, two => 2 }; push @aoh, { three => 3, four => 4 }; push @aoh, { five => 5, six => 6 }; dump_keys( $_ ) for @aoh; sub dump_keys { print "$_\n" for keys %{+shift} }

      Update: jeffa has since revised his answer to make my comment irrelevant.

      But God demonstrates His own love toward us, in that while we were yet sinners, Christ died for us. Romans 5:8 (NASB)

        Why don't you harass the other responses with your pedantry? Everyone in this post used numbered variables because the context was something else --- taking a reference. Please, learn how to read.