在perl中的foreach循环中自动获取循环索引 [英] automatically get loop index in foreach loop in perl
本文介绍了在perl中的foreach循环中自动获取循环索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
@x = qw(a b c);
我用 foreach
来遍历它,那么 $ _
会引用数组中的当前元素:
foreach(@x){
print;
$ / code
$ b $ p
$ b $ p
pre> abc
是否有类似的方法来获取 index 当前元素,而不需要手动更新计数器?例如:
foreach(@x){
print $ index;
其中 $ index
更新如 $ _
以产生输出:
012
解决方案
像codehead说的,你必须迭代数组指标而不是其要素。我更喜欢这个变种,而不是C风格的循环:
$ b
for my $ i(0。 。$#x){
print$ i:$ x [$ i] \\\
;
}
If I have the following array in Perl:
@x = qw(a b c);
and I iterate over it with foreach
, then $_
will refer to the current element in the array:
foreach (@x) {
print;
}
will print:
abc
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;
}
where $index
is updated like $_
to yield the output:
012
解决方案
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]\n";
}
这篇关于在perl中的foreach循环中自动获取循环索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文