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

Whenever I've wanted a persistent variable, I've used the common idiom of declaring a my variable and an accessor inside a block:

{ my $var = 0; sub getvar { $var++ } }
I've just "discovered" a much cleaner way to make a persistant variable. (Or, I'm probably just the only person who's never seen this before.):

print persist(), "\n"; print persist(), "\n"; print persist(), "\n"; sub persist { my $var if 0; ++$var; }

Prints:

1 2 3

This seems far too good to be true. Is it?

Replies are listed 'Best First'.
Re: Persistent variables
by clinton (Priest) on Aug 21, 2007 at 13:04 UTC
    From perlsyn:
    NOTE: The behaviour of a my statement modified with a statement modifier conditional or loop construct (e.g. my $x if ... ) is undefined. The value of the my variable may be undef, any previously assigned value, or possibly anything else. Don't rely on it. Future versions of perl might do something different from the version of perl you try it out on. Here be dragons.

    So it may work now, and break mysteriously later on...

    Clint

      I was aware of that, but had managed to push it to one side in my excitement. I knew it was too good to be true.

      Thanks for pulling my feet back to the ground.

Re: Persistent variables
by snoopy (Curate) on Aug 22, 2007 at 05:55 UTC