本文介绍了在 Perl 中的 foreach 循环中自动获取循环索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我在 Perl 中有以下数组:
If I have the following array in Perl:
@x = qw(a b c);
然后我用 foreach
遍历它,然后 $_
将引用数组中的当前 元素:
and I iterate over it with foreach
, then $_
will refer to the current element in the array:
foreach (@x) {
print;
}
将打印:
abc
是否有类似的方法来获取当前元素的 index,而无需手动更新计数器?诸如:
Is there a similar way to get the index of the current element, without manually updating a counter? Something such as:
foreach (@x) {
print $index;
}
其中 $index
像 $_
一样更新以产生输出:
where $index
is updated like $_
to yield the output:
012
推荐答案
Like codehead 说,你必须迭代数组索引而不是它的元素.与 C 风格的 for
循环相比,我更喜欢这个变体:
Like codehead said, you'd have to iterate over the array indices instead of its elements. I prefer this variant over the C-style for
loop:
for my $i (0 .. $#x) {
print "$i: $x[$i]
";
}
这篇关于在 Perl 中的 foreach 循环中自动获取循环索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!