Why doesn't Perl's each() iterate through

2019-01-12 06:48发布

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,

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-01-12 07:19

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";
查看更多
男人必须洒脱
3楼-- · 2019-01-12 07:24

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.

查看更多
登录 后发表回答