Perl 散列 : while-each-loop runs into endless loop

标签 perl loops hash each infinite-loop

下面的 Perl 代码进入死循环。 看起来 each 在子例程调用后会自行重置。 为什么会这样?

#!/usr/bin/perl
use warnings;
use strict;

my %h = ( "a" => "b" );
while ( my ($x, $y) = each %h ) {
    &do_something( \%h );
}

sub do_something(){
    my %tmp  = %{$_[0]};
}

有趣的是,这有效:

while ( my ($x, $y) = each %h ) {
    &do_something( \%h );
}

sub do_something(){
}

虽然这不是:

while ( my ($x, $y) = each %h ) {
    &do_something( %h );
}

sub do_something(){
}

最佳答案

通过在列表上下文中评估它来获取散列的内容使用与 each/keys/values 相同的迭代器,导致它被重置.

最小演示:

>perl -E"%h=(a=>4); while (($k) = each(%h)) { say $k; keys %h }"
a
a
a
...

>perl -E"%h=(a=>4); while (($k) = each(%h)) { say $k; %t=%h }"
a
a
a
...

由于您仅在第一个和第三个代码段中评估列表上下文中的哈希值,因此迭代器仅在这两个代码段中被重置。


PS — 为什么您使用不正确的原型(prototype) (()) 然后告诉 Perl 忽略它 (&)?

关于Perl 散列 : while-each-loop runs into endless loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12470137/

相关文章:

c - 如何检查输入结束? C、找到42

linux - 菜单和子菜单,然后返回到Linux上的菜单脚本

Java:记住处理哪些对象的有效方法

hash - 我什么时候不使用 HashMap ?

ruby-on-rails - 如何从 hstore 列中获取二维散列作为输出?

c++ - 如何在不使用 com 的情况下在 perl 中调用 C++ dll?

perl - 如何在Windows中杀死进程树

html 标签在 perl 中不起作用

loops - 在ansible中迭代字典中的列表

perl - 将一组父子关系转化为层次结构