Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
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 taking refuge in the Monastery: (4)
As of 2014-09-20 01:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (151 votes), past polls