Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Ouch! Each! Reentrant it is not

by Zaxo (Archbishop)
on Jul 15, 2005 at 02:51 UTC ( #475109=note: print w/replies, xml ) Need Help??


in reply to Ouch! Each! Reentrant it is not

That's a nice demonstration of remembered state with each. It can be a useful property to exploit for some kinds of iterators, but it's pretty fragile. As you say, calling keys on the hash resets the each state.

You can avoid the scalar op and a useless variable by just calling keys in scalar context:

keys %hash and return "The key for 2 is $key\n" if $val == 2;

After Compline,
Zaxo

Replies are listed 'Best First'.
Re^2: Ouch! Each! Reentrant it is not
by Thilosophy (Curate) on Jul 15, 2005 at 03:01 UTC
    You can avoid the scalar op and a useless variable by just calling keys in scalar context

    Taking it one step further, it seems you can also call it in void context (which is maybe more efficient):

    if ($val == 2 ){ keys %hash; return "The key for 2 is $key\n"; }
Re^2: Ouch! Each! Reentrant it is not
by greenFox (Vicar) on Jul 15, 2005 at 03:04 UTC

    You can avoid the scalar op and a useless variable by just calling keys in scalar context:

    I'd want to see that documented in the code or someone will get bitten!

    keys %hash; # reset each to beginning of hash return "The key for 2 is $key\n" if $val == 2;

    --
    Murray Barton
    Do not seek to follow in the footsteps of the wise. Seek what they sought. -Basho

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (5)
As of 2020-06-05 07:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you really want to know if there is extraterrestrial life?



    Results (35 votes). Check out past polls.

    Notices?