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!