perl的每个函数值得使用吗? [英] Is perl's each function worth using?

查看:94
本文介绍了perl的每个函数值得使用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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, 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.

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屋!

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