I have something similar to this:
for (@array) {
print "The value : $_ \n";
print "The current index : ???";
}
But I do not understand, how can I get the current index of @array when looping like this. Please help :)
I have something similar to this:
for (@array) {
print "The value : $_ \n";
print "The current index : ???";
}
But I do not understand, how can I get the current index of @array when looping like this. Please help :)
Don't loop over the array's elements; loop over the array's indexes instead.
for (0 .. $#array) {
print "The value : $array[$_]\n";
print "The current index : $_\n";
}
Given an array called @array, the special variable $#array will contain the index of the last element in the array. Therefore the range 0 .. $#array will produce a list of all of the indexes in the array.
Since Perl 5.12 you can use each for arrays (before it worked only with hashes).
#!/usr/bin/env perl
use strict;
use warnings;
my @array = qw(a b c);
while( my ($idx, $val) = each @array ) {
print "idx=$idx, val=$val\n";
}
Output:
idx=0, val=a
idx=1, val=b
idx=2, val=c
$index variable.each has the same pitfalls regarding the internal counter as it does on hashes.each with arrays. And when, it was as simple as above.