Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: About "state" variables in Perl 5.10

by TimToady (Parson)
on Dec 28, 2007 at 17:49 UTC ( #659362=note: print w/replies, xml ) Need Help??


in reply to About "state" variables in Perl 5.10

There is some overlap in applicability, but the main semantic difference between
{ my $x = 42; my $s = sub { $x++ }; say &$s(); }
and
my $s = sub { state $x = 42; $x++ }; say &$s();
is that the former initializes $x before &$s is created, while the latter does not initialize $x until the first time you call &$s. Note also that with state each created anonymous sub gets its own copy of $x, since technically it's a different lexical scope (or a different pad for the same lexical scope, depending on how you look at it).

This makes little difference with the two snippets above, since in the first example the my also creates a new $x every time you execute the snippet, but if you created $x only once, and then created the closure multiple times in a loop, you'd notice that the single my $x is shared among them.

However, that difference is not why we introduced state variables. The big win is the psychological one of not having to look outside of the sub to find the definition of $x. (That, and we wanted it as a primitive in Perl 6 so that people could write stateful macro constructs without forcing the user to define the state variable externally; in fact, we also use it ourselves in order to implement the stateful flipflop operator without having to build the flipflop in as a primitive, as it is in Perl 5.)

Replies are listed 'Best First'.
Re^2: About "state" variables in Perl 5.10
by citromatik (Curate) on Dec 28, 2007 at 20:22 UTC
    Note also that with state each created anonymous sub gets its own copy of $x

    Hmmm... but you can get the same result with the closure approach:

    sub get_counter { my $x = 42; return sub { $x++; } } my $s = get_counter(); say &$s();
    However, that difference is not why we introduced state variables. The big win is the psychological one of not having to look outside of the sub to find the definition of $x.

    Nice, that reason convince me (and the one that kyle gave below).

    Thanks

    citromatik

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://659362]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (7)
As of 2021-05-13 19:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Perl 7 will be out ...





    Results (142 votes). Check out past polls.

    Notices?