perl - Perl中foreach循环自动获取循环索引

标签 perl foreach

如果我在 Perl 中有以下数组:

@x = qw(a b c);

然后我使用 foreach 对其进行迭代,然后 $_ 将引用数组中当前的元素:

foreach (@x) {
    print;
}

将打印:

abc

是否有类似的方法来获取当前元素的索引,而无需手动更新计数器?例如:

foreach (@x) {
    print $index;
}

其中 $index$_ 一样更新以产生输出:

012

最佳答案

喜欢codehead said ,您必须迭代数组索引而不是其元素。与 C 风格的 for 循环相比,我更喜欢这种变体:

for my $i (0 .. $#x) {
    print "$i: $x[$i]\n";
}

关于perl - Perl中foreach循环自动获取循环索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/974656/

相关文章:

algorithm - 暴力破解我的 gpg 密码

linux - 如何从 Perl 运行和结束 script() linux 命令?

相当于 perl hmac_sha1_hex 的 python

php - 如何使用 php 字典执行 foreach 循环?

php - Mysql INSERT INTO 和 UPDATE 无法正常工作

bash - 您可以为从文件中提取的特定行着色吗?

apache - CGI 脚本 (Perl) 在 Apache 下使用 fastcgi_module 永久运行

javascript - 为什么我的 VowelCount 函数没有返回正确的解决方案?

php - 在 foreach 循环中返回数组

php - 如何只获取foreach中的最后一个值? php