in reply to 'state' variables and unit testing
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:sub global_sum { state $sum = 0; $sum += $_[0]; $sum; }
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; > > sub somefunc > { > state $var = do { > say "Heavy calculations"; > 42+$_[0]; > }; > } > > say somefunc(0); > say somefunc(10); > ' Heavy calculations 42 42
$ perl -e ' > use strict; > use warnings; > use v5.10; > { my $var = 42; > sub somefunc > { > $var + shift; > } > } > say somefunc(5); > say somefunc(10); > ' 47 52
|
|---|