Loop over an array with index and element in the array

Perl looping of an array with index as well as the item stored in variables,


/tmp$ cat loop_with_index.pl 
my @arr=(1,2,3,4);
while (my ($i, $x) = each(@arr)) {
    print "$i: $x\n";
}

/tmp$ perl loop_with_index.pl 
0: 1
1: 2
2: 3
3: 4

Comments

Popular posts from this blog

Multiple repeat error when the regex has multiple wildcards in python re module

Avoid using global/class-level mutable datatypes like list/dicts

Weakref proxy is for instance only ...