views:

510

answers:

3

Hi,

I have a simple script trying to learn about hashes in Perl.

#!/usr/bin/perl

my %set = (
    -a => 'aaa',
    -b => 'bbb',
    -c => 'ccc',
    -d => 'ddd',
    -e => 'eee',
    -f => 'fff',
    -g => 'ggg'
);

print "Iterate up to ggg...\n";
while ( my ($key, $val) = each %set ) {
    print "$key -> $val \n";
    last if ($val eq 'ggg');
}
print "\n";

print "Iterate All...\n";
while ( my ($key, $val) = each %set ) {
    print "$key -> $val \n";
}
print "\n";

I am surprised by the output:-

Iterate upto ggg...
-a -> aaa
-c -> ccc
-g -> ggg

Iterate All...
-f -> fff
-e -> eee
-d -> ddd
-b -> bbb

I understand that the keys are hashed so the first output can be 'n' elements depending on the internal ordering. But why am I not able to just loop the array afterward? What's wrong ?

Thanks,

+11  A: 

each uses a pointer associated with the hash to keep track of iteration. It does not know that the first while is different from the second while loop, and it keeps the same pointer between them.

Most people avoid each for this (and other) reasons, instead opting for keys:

for my $key (keys %hash){
    say "$key => $hash{$key}";
}

This gives you control over the iteration order, as well:

for my $key (sort keys %hash){
    say "$key => $hash{$key}";
}

Anyway, if you are going to end the loop early, avoid each.

BTW, functional programming advocates should take this opportunity to point out the disadvantages of hidden state. What looks like a stateless operation ("loop over each pair in a table") is actually quite stateful.

jrockway
Thanks. BTW, Is it possible to reset 'each' back to the begining ?
"%hash = %hash" seems to work.
jrockway
(perlfaq4 suggests calling "keys" on the hash in void context. This might avoid unnecessary copying.)
jrockway
O.K. Works, Thanks.
+6  A: 

you can read the perldoc on each

perldoc -f each

When the hash is entirely read, a null array is returned in list context (which when assigned produces a false (0) value), and "undef" in scalar context. The next call to "each" after that will start iterating again. There is a sin‐ gle iterator for each hash, shared by all "each", "keys", and "values" function calls in the program; it can be reset by reading all the elements from the hash, or by evaluating "keys HASH" or "values HASH".

therefore, you can use keys %set in your code to iterate again (due to you "last" statement)

print "Iterate upto ggg...\n";
while ( my ($key, $val) = each %set ) {
    print "$key -> $val \n";
    last if ($val eq 'ggg');
}
print "\n";
keys %set;
print "Iterate All...\n";
while ( my ($key, $val) = each %set ) {
    print "$key -> $val \n";
}
print "\n";
ghostdog74
A: 

What's about nested loops? Why my code doesn't print all pairs of hash keys?

    my %h1 = (
        '1' => [1, 2, 3],
        '2' => [2, 3, 4],
        '3' => [3, 4, 5]
    );

    while( my($key1, $value1) = each %h1 )
    {
        while( my($key2, $value2) = each %h1 )
        {
            print "$key1 \t $key2\n";
        }
    }

I want to use each instead of foreach loop because when hash will be really large, I think each will be more efficient than using keys %h1 in foreach.

jesper