Logo

Programming-Idioms

History of Idiom 7 > diff from v131 to v132

Edit summary for version 132 by programming-idioms.org:
[Perl] Variable names, for arrays only

Version 131

2022-08-26, 14:35:08

Version 132

2022-08-27, 16:18:17

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

Variables
i,x,items
Variables
i,x,items
Extra Keywords
indices traverse traversal
Extra Keywords
indices traverse traversal
Imports
use 5.012; # each @array
Imports
use 5.012; # each @array
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";
}
Code
while (my ($i, $x) = each @items) {
    print "array[$i] = $x\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
Doc URL
http://p3rl.org/each