citromatik has asked for the wisdom of the Perl Monks concerning the following question:
Hi all
"state variables" are a new feature in Perl 5.10 that "are similar to my variables, but are declared with the state keyword in place of my. They're visible only in their lexical scope, but their value is persistent: unlike my variables, they're not undefined at scope entry, but retain their previous value."
So, as I understand this, this new kind of variables is like "static" variables in C and allow you to write code like:
sub counter { state $count = 0; $count++; }
Before Perl 5.10 you can do that with:
{ my $count = 0; sub counter { $count++; } }
This way allows you to share a common $count variable between more than one sub:
{ my $count = 0; sub counter1 { $count++; } sub counter2 { $count += 2; } }
Since I find the latter very simple to follow and understand I would like to know if there are differences between them and when one or the other should be used
Thanks in advance!
citromatik
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: About "state" variables in Perl 5.10
by TimToady (Parson) on Dec 28, 2007 at 17:49 UTC | |
by citromatik (Curate) on Dec 28, 2007 at 20:22 UTC | |
Re: About "state" variables in Perl 5.10
by kyle (Abbot) on Dec 28, 2007 at 18:04 UTC | |
by citromatik (Curate) on Dec 29, 2007 at 12:58 UTC | |
Re: About "state" variables in Perl 5.10
by Limbic~Region (Chancellor) on Dec 28, 2007 at 18:48 UTC | |
Re: About "state" variables in Perl 5.10
by shmem (Chancellor) on Dec 28, 2007 at 16:48 UTC | |
Re: About "state" variables in Perl 5.10
by exussum0 (Vicar) on Dec 28, 2007 at 18:46 UTC | |
by grinder (Bishop) on Dec 28, 2007 at 22:30 UTC | |
by tye (Sage) on Dec 29, 2007 at 03:18 UTC |