randian has asked for the wisdom of the Perl Monks concerning the following question:

#!/usr/bin/env perl #-*-Perl-*- use v5.16; my @a = qw<a b c>; my $b = [@a]; while (my ($i, $v) = each $b) { say "$i: $v"; } while (my ($i, $v) = each [@a]) { say "$i: $v"; }
Trying out the arrayref functionality introduced in 5.14. The first loop executes the expected 3 times, printing the expected values. The second loops infinitely, always giving 0 for $i and 'a' for $v. Hashrefs display the same behavior.
my $b = {map { $_ => $_ } qw<a b c>}; while (my ($i, $v) = each $b) { say "$i: $v"; } while (my ($i, $v) = each {map { $_ => $_ } qw<a b c>}) { say "$i: $v"; }

Replies are listed 'Best First'.
Re: perl v5.16 bug?
by dave_the_m (Monsignor) on Mar 15, 2013 at 23:28 UTC
    With each [@a], you create a new anonymous array in every iteration of the condition of the while loop, and process its zeroth element

    Dave.

      Duh! Thanks for the correction.
Re: perl v5.16 bug?
by tobyink (Canon) on Mar 15, 2013 at 23:38 UTC

    The problem is that the entire while condition is evaluated every time around the loop, meaning that [@a] is evaluated every time around the loop, yielding a reference to a different anonymous array every time around the loop.

    Because you're polling a fresh new array every time around the loop, each's "pointer" for the array is at the beginning every time.

    This is the safe way to do it:

    while (my ($i, $v) = each \@a) { say "$i: $v"; }

    ... because you're using a reference to the same array every time around the loop.

    package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name
Re: perl v5.16 bug? (:sure:)
by Anonymous Monk on Mar 16, 2013 at 07:05 UTC
      Nit: That the feature was introduced in 2011 (not 1987) and that it's still marked as experimental changes the dynamic somewhat.