Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: 'state' variables and unit testing

by Laurent_R (Canon)
on Feb 02, 2014 at 23:52 UTC ( [id://1073106]=note: print w/replies, xml ) Need Help??


in reply to 'state' variables and unit testing

Hmm, state variables are in my view a useful addition to Perl, but not quite as useful as closure variables. They are also a bit counter-intuitive, as in the following example provided by the OP:
sub global_sum { state $sum = 0; $sum += $_[0]; $sum; }
If I don't know what state is doing, I might think that $sum is reset to 0 each time through the sub, and I get a totally wrong idea of what the sub is really doing. It is not really obvious that the first line in that sub is executed only the first time through the sub and not in the next calls. Also, consider this example:
$ perl -e ' > use strict; > use warnings; > use v5.10; > > sub somefunc > { > state $var = do { > say "Heavy calculations"; > 42+$_[0]; > }; > } > > say somefunc(0); > say somefunc(10); > ' Heavy calculations 42 42
Although it is quite easy to explain what is going on, I would submit that this can be unexpected. The following code, using a closure, is more along the line of the behavior you would probably want:
$ perl -e ' > use strict; > use warnings; > use v5.10; > { my $var = 42; > sub somefunc > { > $var + shift; > } > } > say somefunc(5); > say somefunc(10); > ' 47 52

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (4)
As of 2024-04-23 15:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found