Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Each on anonymous hash is causing endless loop.

by LanX (Saint)
on Aug 24, 2022 at 20:35 UTC ( [id://11146384]=perlquestion: print w/replies, xml ) Need Help??

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

ehm ... I just stumbled over a strange effect when using each on an anonymous hash.

Bug or feature?

C:\>perl my $hr = {a=>1,b=>2}; $\="\n"; while ( my ($k,$v) = each %{ $hr } ) { print qq($k => $v) } __END__ b => 2 a => 1 C:\>perl $\="\n"; $x=10; while ( my ($k,$v) = each %{ {a=>1,b=>2} } ) { print qq($k => $v); die + "abort" unless $x-- } __END__ b => 2 b => 2 a => 1 b => 2 a => 1 a => 1 b => 2 b => 2 a => 1 a => 1 a => 1 abort at - line 2. C:\>perl -E"say $]" 5.032001

Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery

Replies are listed 'Best First'.
Re: Each on anonymous hash is causing endless loop.
by tybalt89 (Monsignor) on Aug 24, 2022 at 21:14 UTC

    Why strange? It's a new hash every iteration. This is expected behavior.

      Thanks, good explanation!

      I was expecting some kind of constant folding ...

      C:\>perl -M5.012 my $x = 5; while ( say {a=>1,b=>2} ) { die "abort" unless --$x } __END__ HASH(0xf5b3d0) HASH(0xf5b508) HASH(0xf5b3d0) HASH(0xf5b508) HASH(0xf5b3d0) abort at - line 2. C:\>

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      Wikisyntax for the Monastery

Re: Each on anonymous hash is causing endless loop.
by choroba (Cardinal) on Aug 24, 2022 at 20:57 UTC
    say while $_ = shift @{ [1 .. 10] }; # Never stops, either.

    map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://11146384]
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (5)
As of 2024-03-28 14:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found