Skip to content

Commit 77b7888

Browse files
Grinnzkhwilliamson
authored andcommitted
perlfunc - update each documentation with foreach examples
Also mention multiple-value foreach as a new alternative, and fix a hash dereference in a previous example.
1 parent c669642 commit 77b7888

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

.mailmap

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,7 @@ Cygwin <cygwin@cygwin.com> cygwin@cygwin.com <cygwin@cygwin.com>
230230
Dagfinn Ilmari Mannsåker <ilmari@ilmari.org> Dagfinn Ilmari Mannsåker (via RT) <perlbug-followup@perl.org>
231231
Dagfinn Ilmari Mannsåker <ilmari@ilmari.org> ilmari@vesla.ilmari.org <ilmari@vesla.ilmari.org>
232232
Damian Conway <damian@conway.org> Damian Conway <damian@cs.monash.edu.au>
233+
Dan Book <grinnz@grinnz.com> Dan <grinnz@grinnz.com>
233234
Dan Dascalescu <bigbang7@gmail.com> Dan Dascalescu <ddascalescu+github@gmail.com>
234235
Dan Faigin <unknown> Dan Faigin, Doug Landauer <unknown@longtimeago>
235236
Dan Jacobson <jidanni@jidanni.org> Dan Jacobson <jidanni@hoffa.dreamhost.com>

pod/perlfunc.pod

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2126,15 +2126,33 @@ accidentally clobber the iterator state during execution of the loop body.
21262126
It's easy enough to explicitly reset the iterator before starting a loop,
21272127
but there is no way to insulate the iterator state used by a loop from
21282128
the iterator state used by anything else that might execute during the
2129-
loop body. To avoid these problems, use a C<foreach> loop rather than
2130-
C<while>-C<each>.
2129+
loop body.
21312130

21322131
This extends to using C<each> on the result of an anonymous hash or
21332132
array constructor. A new underlying array or hash is created each
21342133
time so each will always start iterating from scratch, eg:
21352134

21362135
# loops forever
2137-
while (my ($key, $value) = each @{ +{ a => 1 } }) {
2136+
while (my ($key, $value) = each %{ +{ a => 1 } }) {
2137+
print "$key=$value\n";
2138+
}
2139+
2140+
To avoid these problems resulting from the hash-embedded iterator, use a
2141+
L<C<foreach>|perlsyn/"Foreach Loops"> loop rather than C<while>-C<each>.
2142+
As of Perl 5.36, you can iterate over both keys and values directly with
2143+
a multiple-value C<foreach> loop.
2144+
2145+
# retrieves the keys one time for iteration
2146+
# iteration is unaffected by any operations on %hash within
2147+
foreach my $key (keys %hash) {
2148+
my $value = $hash{$key};
2149+
$hash{$key} = {keys => scalar keys %hash, outer => [%hash]};
2150+
some_function_that_may_mess_with(\%hash, $key, $value);
2151+
$hash{"new$key"} = delete $hash{$key};
2152+
}
2153+
2154+
# Perl 5.36+
2155+
foreach my ($key, $value) (%{ +{ a => 1 } }) {
21382156
print "$key=$value\n";
21392157
}
21402158

0 commit comments

Comments
 (0)