Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

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"; }

Comment on perl v5.16 bug?
Select or Download Code
Re: perl v5.16 bug?
by dave_the_m (Parson) 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 (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?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1023793]
Approved by davido
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (8)
As of 2014-08-28 10:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (259 votes), past polls