From 77b78882c76e7461ccc4dcf2eb3afb9644836a72 Mon Sep 17 00:00:00 2001 From: Dan Date: Fri, 27 Sep 2024 15:35:03 -0400 Subject: [PATCH] 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. --- .mailmap | 1 + pod/perlfunc.pod | 24 +++++++++++++++++++++--- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/.mailmap b/.mailmap index ea6ecedcf3d7..73ad91b1c2e6 100644 --- a/.mailmap +++ b/.mailmap @@ -230,6 +230,7 @@ Cygwin cygwin@cygwin.com Dagfinn Ilmari Mannsåker Dagfinn Ilmari Mannsåker (via RT) Dagfinn Ilmari Mannsåker ilmari@vesla.ilmari.org Damian Conway Damian Conway +Dan Book Dan Dan Dascalescu Dan Dascalescu Dan Faigin Dan Faigin, Doug Landauer Dan Jacobson Dan Jacobson diff --git a/pod/perlfunc.pod b/pod/perlfunc.pod index a6ee7aeaa0a0..27671e36ffde 100644 --- a/pod/perlfunc.pod +++ b/pod/perlfunc.pod @@ -2126,15 +2126,33 @@ accidentally clobber the iterator state during execution of the loop body. It's easy enough to explicitly reset the iterator before starting a loop, but there is no way to insulate the iterator state used by a loop from the iterator state used by anything else that might execute during the -loop body. To avoid these problems, use a C loop rather than -C-C. +loop body. This extends to using C on the result of an anonymous hash or array constructor. A new underlying array or hash is created each time so each will always start iterating from scratch, eg: # loops forever - while (my ($key, $value) = each @{ +{ a => 1 } }) { + while (my ($key, $value) = each %{ +{ a => 1 } }) { + print "$key=$value\n"; + } + +To avoid these problems resulting from the hash-embedded iterator, use a +L|perlsyn/"Foreach Loops"> loop rather than C-C. +As of Perl 5.36, you can iterate over both keys and values directly with +a multiple-value C loop. + + # retrieves the keys one time for iteration + # iteration is unaffected by any operations on %hash within + foreach my $key (keys %hash) { + my $value = $hash{$key}; + $hash{$key} = {keys => scalar keys %hash, outer => [%hash]}; + some_function_that_may_mess_with(\%hash, $key, $value); + $hash{"new$key"} = delete $hash{$key}; + } + + # Perl 5.36+ + foreach my ($key, $value) (%{ +{ a => 1 } }) { print "$key=$value\n"; }