There's an iterator stored in with each hash

来源:互联网 发布:智能电视怎么连接网络 编辑:程序博客网 时间:2024/06/04 20:25
This is the 14-th footnote in Chapter 5 of Oreilly--Learning Perl(3rd) .

[14]
Since each hash has its own private iterator, loops using each may be nested, as long as they are iterating over different hashes. And, as long as we're already in a footnote, we may as well tell you: it's unlikely you'll ever need to do so, but you may reset the iterator of a hash by using the keys or values function on the hash. The iterator is also automatically reset if a new list is stored into the entire hash, or if each has iterated through all of the items to the "end" of the hash. On the other hand, adding new key-value pairs to the hash while iterating over it is generally a bad idea, since that won't necessarily reset the iterator. That's likely to confuse you, your maintenance programmer, and each as well

Pay great attention to it please.
 
Look into this example:

#-----------------------------------------------------------------------------
my %ahash = ("a" => 1, "b" => 2, "c" =>3, "d" =>4");
my $index = 0;
while($index < 3) {
  while (my ($key, $val) = each %ahash) {
       print "$key ==> $val/n";
       if ($key eq "b") {
          last;
       }
  }
  $index++;
}

#-----------------------------------------------------------------------------

Assume that the each function returns the pair of key-value by the order they are assigned.
Do you think this piece of function will print:
a ==> 1
b ==> 2
a ==> 1
b ==> 2

a ==> 1
b ==> 2


No!
Totally wrong!
In fact, It will print
a ==> 1
b ==> 2  ($index == 0)
c ==> 3
d ==> 4  ($index == 1, and here while containing each ends)
a ==> 1
b ==> 2
($index == 2)

Why? There's an iterator stored in with each hash.
The iterator will go in its internal way, no matter what happens external.
And the iterator will NOT reset to the beginning unless you do.
How to reset it? See the 14-th footnote.

How to iterate the hash from the beginning every time?
Use keys function, also see the footnote.



原创粉丝点击