1

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 :)

1
  • @toolic That's what I thought to use. But I was trying to search, if there is something built in available. I didn't find any, so posted. Commented Nov 20, 2017 at 14:53

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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

6 Comments

Mine is perl 5.10.1. I see : Type of arg 1 to each must be hash (not private array) at test.pl line 8, near "@array ) " Execution of test.pl aborted due to compilation errors.
Damn. Bad luck. Then you have to use a separate $index variable.
I wonder if that use of each has the same pitfalls regarding the internal counter as it does on hashes.
@PerlDuck Yeah, I am using something like that now. Thank you so much. Thanks Dave :)
@simbabque Interesting question. I've no idea and only rarely used each with arrays. And when, it was as simple as above.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.