There's an iterator stored in with each hash

本文深入探讨了Perl语言中哈希数据结构的迭代方法,特别是使用each函数进行迭代的过程及注意事项。通过一个具体示例解释了哈希迭代器的工作原理,并提供了如何重置迭代器的建议。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值