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

I have several hashes, %a %b %c etc. Each of these hashes contain the same keys, but different values. I need to compare the values within %a to other values within %a, and the values within %b in the same manner. I have tried for %x(%a,%b,%c), yet this does not work. Is it possible to loop over a block of code using a list of hashes, and if so, how?

Replies are listed 'Best First'.
Re: Looping with hashes?
by toolic (Bishop) on Jan 23, 2009 at 01:28 UTC
    If you show your actual Perl code (inside "code" tags), you should receive detailed answers. Also provide more information on how it "does not work". Show any warning or error messages, expected output and actual output.

    Since you have three hashes, I would think you would want three separate loops, unless you are comparing a values to b and c values.

    You may also consider reorganizing your data to be in a single hash-of-arrays structure, since your 3 hashes have identical keys. You would still need the same looping for your comparisons, but a single structure would guarantee coherence, and the relationship amongst your data sets would be more apparent.

Re: Looping with hashes?
by ikegami (Patriarch) on Jan 23, 2009 at 02:53 UTC
    for (keys %a) print("$a{$_}\n"); print("$b{$_}\n"); print("$c{$_}\n"); }
Re: Looping with hashes?
by poolpi (Hermit) on Jan 23, 2009 at 08:28 UTC

    If you want to loop over your hashes, you can use references:

    for( \%a, \%b, \%c ){ print sort keys %$_, "\n"; }

    You can mix all hashes in one
    (See above, toolic's node)

    #!/usr/bin/perl use strict; use warnings; use Data::Dumper; my $a = { 1 => 'a', 2 => 'b', 3 => 'c' }; my $b = { 1 => 'd', 2 => 'e', 3 => 'f' }; my $c = { 1 => 'g', 2 => 'h', 3 => 'i' }; my $abc; for my $h_ref ( $a, $b, $c ){ for my $key (keys %$a){ push @{ $abc->{$key} }, $h_ref->{$key}; } } print Dumper $abc; __END__ $VAR1 = { '1' => [ 'a', 'd', 'g' ], '3' => [ 'c', 'f', 'i' ], '2' => [ 'b', 'e', 'h' ] };


    hth,
    PooLpi

    'Ebry haffa hoe hab im tik a bush'. Jamaican proverb
Re: Looping with hashes?
by setebos (Beadle) on Jan 23, 2009 at 02:54 UTC
    perldoc -q sort and perldoc -f sort
    are your friends.
    Also take a look at man perldoc.