为什么 Perl 的 each() 不第二次遍历整个散列? [英] Why doesn't Perl's each() iterate through the entire hash the second time?

查看:24
本文介绍了为什么 Perl 的 each() 不第二次遍历整个散列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的脚本试图了解 Perl 中的散列.

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...
";
while ( my ($key, $val) = each %set ) {
    print "$key -> $val 
";
    last if ($val eq 'ggg');
}
print "
";

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

我对输出感到惊讶:-

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

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

我知道键是经过哈希处理的,因此第一个输出可以是n"个元素,具体取决于内部顺序.但是为什么我不能在之后循环数组?怎么了 ?

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 ?

谢谢,

推荐答案

each 使用与散列关联的指针来跟踪迭代.它不知道第一个 while 循环与第二个 while 循环不同,并且在它们之间保持相同的指针.

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.

大多数人出于这个(和其他)原因避免使用 each,而是选择 keys:

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}";
}

无论如何,如果您要提前结束循环,请避免each.

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.

这篇关于为什么 Perl 的 each() 不第二次遍历整个散列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆