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:
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.):{ my $var = 0; sub getvar { $var++ } }
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 | |
by FunkyMonk (Bishop) on Aug 21, 2007 at 13:10 UTC | |
|
Re: Persistent variables
by snoopy (Curate) on Aug 22, 2007 at 05:55 UTC |