微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

数组 – 在标量上下文中新的“每个@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),因为它是假的.

原文地址:https://www.jb51.cc/Perl/171538.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐