- each EXPR
When called on a hash in list context, returns a 2-element list consisting of the key and value for the next element of a hash. In Perl 5.12 and later only, it will also return the index and value for the next element of an array so that you can iterate over it; older Perls consider this a syntax error. When called in scalar context, returns only the key (not the value) in a hash, or the index in an array.
Hash entries are returned in an apparently random order. The actual random order is subject to change in future versions of Perl, but it is guaranteed to be in the same order as either the
valuesfunction would produce on the same (unmodified) hash. Since Perl 5.8.2 the ordering can be different even between different runs of Perl for security reasons (see Algorithmic Complexity Attacks in perlsec).
eachhas returned all entries from the hash or array, the next call to
eachreturns the empty list in list context and
undefin scalar context; the next call following that one restarts iteration. Each hash or array has its own internal iterator, accessed by
values. The iterator is implicitly reset when
eachhas reached the end as just described; it can be explicitly reset by calling
valueson the hash or array. If you add or delete a hash's elements while iterating over it, entries may be skipped or duplicated--so don't do that. Exception: In the current implementation, it is always safe to delete the item most recently returned by
each(), so the following code works properly:
This prints out your environment like the printenv(1) program, but in a different order:
Starting with Perl 5.14,
eachcan take a scalar EXPR, which must hold reference to an unblessed hash or array. The argument will be dereferenced automatically. This aspect of
eachis considered highly experimental. The exact behaviour may change in a future version of Perl.
To avoid confusing would-be users of your code who are running earlier versions of Perl with mysterious syntax errors, put this sort of thing at the top of your file to signal that your code will work only on Perls of a recent vintage: