perl的每个函数值得使用吗? [英] Is perl's each function worth using?
问题描述
从 perldoc -f each 我们看到:
每个散列都有一个迭代器,由所有
每个
,键共享
和
values
程序中的函数调用;它可以通过读取散列中的所有元素或通过评估键HASH
或值HASH
来重置。当你离开包含each()
的作用域时,迭代器不会被重置,这可能会导致错误:my%h = map {$ _,1} qw(1 2 3);
while(my $ k = each%h){print1:$ k\\\
; ($ k = each%h){print2:$ k\\\
}
输出:
1:1
2:3
2:2
这种行为常见的解决方法是什么?是否值得一般使用
每个
?解决方案值得使用,只要你知道这一点。当你需要迭代中的键和值时,它是理想的:
while(my($ k,$ v)= each%h ){
说$ k = $ v;
$ b $ p
$ b在你的例子中,你可以通过添加
来重置迭代器,键%h;
就像这样:
my%h = map {$ _ => 1} qw / 1 2 3 /;
while(my $ k = each%h){print1:$ k\\\
;最后}
键%h; #reset%h
while(my $ k = each%h){print2:$ k\\\
}
来自Perl 5.12
每个
也允许迭代数组。From perldoc -f each we read:
There is a single iterator for each hash, shared by all
each
,keys
, andvalues
function calls in the program; it can be reset by reading all the elements from the hash, or by evaluatingkeys HASH
orvalues HASH
.The iterator is not reset when you leave the scope containing the
each()
, and this can lead to bugs:my %h = map { $_, 1 } qw(1 2 3); while (my $k = each %h) { print "1: $k\n"; last } while (my $k = each %h) { print "2: $k\n" }
Output:
1: 1 2: 3 2: 2
What are the common workarounds for this behavior? And is it worth using
each
in general?解决方案I think it is worth using as long as you are aware of this. It's ideal when you need both key and value in iteration:
while (my ($k,$v) = each %h) { say "$k = $v"; }
In your example you can reset the iterator by adding
keys %h;
like so:my %h = map { $_ => 1 } qw/1 2 3/; while (my $k = each %h) { print "1: $k\n"; last } keys %h; # reset %h while (my $k = each %h) { print "2: $k\n" }
From Perl 5.12
each
will also allow iteration on an array.这篇关于perl的每个函数值得使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!