DavidSzczesniak
12/11/2017 - 3:40 PM

The 'each' operator

Each returns two values for the next element in the array - the index of the value and the value itself.

@rocks qw/ bedrock slate rubble granite /;
while(($index, $value) = each @rocks) { # iterates through each element in the @rocks array
  print "$index: $value\n"; # prints every value with its index
}

# Without each, you would have to iterate through all of the indices of the array, 
# and use the index to get the value:
@rocks = qw/ bedrock slate rubble granite /;
foreach $index (0..$#rocks) {
  print "$index: $rocks[$index]\n";
}