http://www.perlmonks.org?node_id=1020128

default_user has asked for the wisdom of the Perl Monks concerning the following question:

In the following example I create an additional variable to keep track where I am in the array.
my @SampleArray = ("one","two","three" ); my $Arrayindex = 0; foreach my $ArrayItem ( @SampleArray ){ print $ArrayItem , ' is at location ' , $Arrayindex , ' in the arr +ay' , "\n"; $Arrayindex++; }
The question, is there a more efficient way to do this? I don't like having to use the $Arrayindex++; method to achieve this.

Replies are listed 'Best First'.
Re: Index of Items in Array using foreach loop
by tobyink (Canon) on Feb 22, 2013 at 10:50 UTC

    Don't loop through the array; loop through the indices!

    use strict; use warnings; my @SampleArray = ("one", "two", "three"); for my $ArrayIndex ( 0 .. $#SampleArray ) { printf( "%s is at location %d in the array\n", $SampleArray[$ArrayIndex], $ArrayIndex, ); }

    Or just use a sufficiently modern version of Perl...

    use v5.12; use strict; use warnings; my @SampleArray = ("one", "two", "three"); while (my ($ArrayIndex, $ArrayItem) = each @SampleArray) { printf( "%s is at location %d in the array\n", $ArrayItem, $ArrayIndex, ); }

    Update: Although each @array was only added to Perl as of 5.12, Array::Each::Override provides a working implementation of each @array for Perl going back to 5.8.

    package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name
Re: Index of Items in Array using foreach loop
by tmharish (Friar) on Feb 22, 2013 at 10:48 UTC

    Yes - use the for loop:

    for( my $Arrayindex = 0; $Arrayindex <= ( $#SampleArray ); $Arrayindex +++ ) { print $SampleArray[ $Arrayindex ] , ' is at location ' , $Arr +ayindex , ' in the array' , "\n"; }