Logo

Programming-Idioms

History of Idiom 7 > diff from v77 to v78

Edit summary for version 78 by daxim:
[Perl] add docs, fix name of array index, indicate version requirement for `each @array`

Version 77

2019-09-29, 15:20:47

Version 78

2019-09-29, 17:10:14

Idiom #7 Iterate over list indexes and values

Print each index i with its value x from an array-like collection items

Idiom #7 Iterate over list indexes and values

Print each index i with its value x from an array-like collection items

Extra Keywords
traverse traversal
Extra Keywords
traverse traversal
Imports
Imports
use 5.012; # each @array
Code
# For an array
while ( ($idx, $val) = each @array) {
   print "array[$i] = $val\n";
}

# For a hash
while ( ($key, $val) = each %hash) {
   print "hash{$key} = $val\n";
}
Code
# For an array
while (my ($idx, $val) = each @array) {
    print "array[$idx] = $val\n";
}

# For a hash
while (my ($key, $val) = each %hash) {
    print "hash{$key} = $val\n";
}
Comments bubble
The each iterator returns the index/key and value as a pair for each iteration.
Comments bubble
The each iterator returns the index/key and value as a pair for each iteration.
Doc URL
http://p3rl.org/each