in reply to Interesting Use for "state" Variables

You can "save" the state if you use it in the declaration, not the execution part:
use feature ":5.10"; my %hash = map { $_ => state $i++ } qw(red blue green yellow black whi +te purple brown orange gray); for (1..2) { while (($k,$v) = each %hash) { do_something_with($k, $v); } }
(Defined execution order left as exercise for the reader)

Search, Ask, Know

Replies are listed 'Best First'.
Re^2: Interesting Use for "state" Variables
by JavaFan (Canon) on Mar 10, 2009 at 22:36 UTC
    for (1..2) { while (($k,$v) = each %hash) { do_something_with($k, $v); } }
    Talking about state, you know your code may not do what you expect it to do, don't you? 'each' is an iterator which keeps state on the hash itself. Which means that if the loop exits prematurely (which could even happen in this code if do_something_with contains a 'last') the next time around, it will iterate over the entire hash.

    You may want to develop the habit to write keys %hash; in void or scalar context right before each each. (It's not an easy habit to get used to - each isn't common enough for that - half of the time, I forget it my own good advice).