Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

perl v5.16 bug?

by randian (Acolyte)
on Mar 15, 2013 at 23:15 UTC ( #1023793=perlquestion: print w/replies, xml ) Need Help??
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 (Prior) 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


      Duh! Thanks for the correction.
Re: perl v5.16 bug?
by tobyink (Abbot) 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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1023793]
Approved by davido
[planetscape]: sleep well, Corion
[stonecolddevin]: erix seems pretty good, i listened to "So Many Roads" and it was nice. Not everyone's cup of tea but this guy can absolutely shred, he and the guy from Mastodon are definitely up there: https://www. v=VzhMkSN9dQc
[erix]: ha, good stuff - loud and fast...
[stonecolddevin]: here's some Mastodon for when you have 13 minutes to have your mind blown: https://www. v=4pvfQtUhtNE
[karlgoethebier]: goes to Brownsville one more time..

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (9)
As of 2017-06-22 21:48 GMT
Find Nodes?
    Voting Booth?
    How many monitors do you use while coding?

    Results (531 votes). Check out past polls.