http://www.perlmonks.org?node_id=571084


in reply to Perl 5.9.4 released

re state variables, do I read it correctly that we would no longer have to write:

{ my $stately; sub some_func { # use $stately here } }

to get a variable which maintains it's state? Neat. Can any-one give us a glimpse of the internals and let us know how that is done? My random guess: turn off garbage collection for state variables?

--
Do not seek to follow in the footsteps of the wise. Seek what they sought. -Basho

Replies are listed 'Best First'.
Re^2: Perl 5.9.4 released
by theorbtwo (Prior) on Sep 04, 2006 at 14:21 UTC

    Kind of. When you say sub foo {my $bar}, perl doesn't actually allocate a new variable every time you execute foo. Instead, it just clears the value. When you say state $bar it doesn't do that either. (This gets into the variable/value split, which is generally not talked about much in perl5-land. Suffice it to say, I did mean to say "variable" and "value" when I did.)


    Warning: Unless otherwise stated, code is untested. Do not use without understanding. Code is posted in the hopes it is useful, but without warranty. All copyrights are relinquished into the public domain unless otherwise stated. I am not an angel. I am capable of error, and err on a fairly regular basis. If I made a mistake, please let me know (such as by replying to this node).

Re^2: Perl 5.9.4 released
by grinder (Bishop) on Sep 04, 2006 at 16:20 UTC

    The main motivation behind state variables in perl5 land was to get rid of the awful hack:

    my $var if 0;

    Which was a way of getting state variables, but worked on an undocumented side-effect of how lexical pads are implemented. And the code is neater than having to close a an external variable over a routine.

    The main patch (although there were a few tweaks a couple of months later as kinks were ironed out), as landed in the repository, is quite small, all things considered.

    Basically it's just a tweak on lexical variables.

    Another nifty feature of 5.9.4 is that $_ can be made lexical.

    • another intruder with the mooring in the heart of the Perl

Re^2: Perl 5.9.4 released
by Limbic~Region (Chancellor) on Sep 04, 2006 at 14:33 UTC