since 5.10 there is "state" statement, making this pattern even more easy.use strict; use warnings; use v5.10; our $_cached; sub somefunc { $_cached //= do { say "Heavy calculations"; 42+($ARGV[0]||0); }; } say somefunc(); say somefunc(); __END__ Heavy calculations 42 42
use strict; use warnings; use v5.10; sub somefunc { state $var = do { say "Heavy calculations"; 42+($ARGV[0]||0); }; } say somefunc(); say somefunc(); __END__ Heavy calculations 42 42
However I see one problem here: unit testing.
With first example it's easy to test somefunc with several possible inputs.
{ local $_cached = undef; local @ARGV = (3); say somefunc(); } { local $_cached = undef; local @ARGV = (5); say somefunc(); }
and with "state" it looks impossible? Once you call somefunc() from your test, it's result cached forever.
Looks like a missing important feature, which can encourage people not using unit testing? What do you think?
In reply to 'state' variables and unit testing by vsespb
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |