数组 – 在标量上下文中新的“每个@array”的行为

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'

也不输出任何输出. s’@ array’@ a’oops.

编辑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),因为它是假的.

相关文章

1. 如何去重 #!/usr/bin/perl use strict; my %hash; while(...
最近写了一个perl脚本,实现的功能是将表格中其中两列的数据...
表的数据字典格式如下:如果手动写MySQL建表语句,确认麻烦,...
巡检类工作经常会出具日报,最近在原有日报的基础上又新增了...
在实际生产环境中,常常需要从后台日志中截取报文,报文的形...
最近写的一个perl程序,通过关键词匹配统计其出现的频率,让...