Perl 5.14给我们扩展了对数组和散列进行操作的每个函数:
When called in list context,returns a 2-element list consisting of the key and value for the next element of a hash,or the index and value for the next element of an array,so that you can iterate over it. When called in scalar context,returns only the key (not the value) in a hash,or the index in an array.
使用列表上下文的示例工作:
perl -E 'say $^V' v5.14.0 perl -E '@a = (1..10); while (my ($i,$elem) = each @a) {say "\$a[$i] = $elem"}' $a[0] = 1 $a[1] = 2 $a[2] = 3 $a[3] = 4 $a[4] = 5 $a[5] = 6 $a[6] = 7 $a[7] = 8 $a[8] = 9 $a[9] = 10
然而在标量语境中,我什么也没有:
perl -E '@a = (1..10); while (my $i = each @a) {say $i}'
任何人都可以提供任何见解?我有一种感觉,当有人指出我的错误,但也许不是这样,这将是一个头痛.
编辑:实际上while循环与它无关:
perl -E '@a = (1..10); $i = each @array; say $i'
编辑2:
根据daxim的评论:
perl -MDevel::Peek -E'@a = (1..10); Dump each @a' SV = IV(0x161ce58) at 0x161ce68 REFCNT = 1 FLAGS = (TEMP,IOK,pIOK) IV = 0
但是我不知道该告诉我什么.
编辑3:
似乎循环退出,因为第一个索引是0或false.我已经提交了一个错误(http://rt.perl.org/rt3/Ticket/Display.html?id=90888),因为这似乎不是所期望的行为.
解决方法
你需要做(while(我的$i =每个@array)){说$i}否则它会停在第一个索引(0),因为它是假的.