Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

Re: Optimization, side-effects and wrong code

by dragonchild (Archbishop)
on Sep 29, 2004 at 18:20 UTC ( #395092=note: print w/replies, xml ) Need Help??

in reply to Optimization, side-effects and wrong code

I KNEW I'd read something about this before. p383 in Programming Perl, 3rd ed.

By calling keys in a scalar context, we reset its internal state to ensure that the next each used in the return statement will get the first key.

sub find_stuff { my $self = shift; scalar keys %$self; while (my $k = each %$self) { return $k if ($self->{$k}->{blablah}); } return undef; }

Being right, does not endow the right to be rude; politeness costs nothing.
Being unknowing, is not the same as being stupid.
Expressing a contrary opinion, whether to the individual or the group, is more often a sign of deeper thought than of cantankerous belligerence.
Do not mistake your goals as the only goals; your opinion as the only opinion; your confidence as correctness. Saying you know better is not the same as explaining you know better.

I shouldn't have to say this, but any code, unless otherwise stated, is untested

Replies are listed 'Best First'.
Re^2: Optimization, side-effects and wrong code
by cbraga (Pilgrim) on Sep 29, 2004 at 18:25 UTC
    Thanks for the tip. I guess it should be printed in bold in each's manpage.

    ESC[78;89;13p ESC[110;121;13p

      It is noted in the POD for keys:

      As a side effect, calling keys() resets the HASH's internal iterator, see each. (In particular, calling keys() in void context resets the iterator with no other overhead.)

      Examine what is said, not who speaks.
      "Efficiency is intelligent laziness." -David Dunham
      "Think for yourself!" - Abigail
      "Memory, processor, disk in that order on the hardware side. Algorithm, algorithm, algorithm on the code side." - tachyon
        I had the misfortune of getting caught out by this the other day. I decided to call 'keys' inside a while (each) loop... this reset the pointer, causing an infinite loop :/

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://395092]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (15)
As of 2018-06-22 15:29 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (124 votes). Check out past polls.