且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在perl中的foreach循环中自动获取循环索引

更新时间:2022-10-15 18:47:18

像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";
}