There is common pattern to cache result of heavy calculations.
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?
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: 'state' variables and unit testing
by moritz (Cardinal) on Feb 01, 2014 at 19:59 UTC | |
by tye (Sage) on Feb 01, 2014 at 22:36 UTC | |
by vsespb (Chaplain) on Feb 01, 2014 at 20:44 UTC | |
by moritz (Cardinal) on Feb 01, 2014 at 20:57 UTC | |
by Jenda (Abbot) on Feb 02, 2014 at 02:06 UTC | |
by tye (Sage) on Feb 02, 2014 at 02:27 UTC | |
by Jenda (Abbot) on Feb 02, 2014 at 12:10 UTC | |
| |
Re: 'state' variables and unit testing (our)
by tye (Sage) on Feb 01, 2014 at 17:50 UTC | |
Re: 'state' variables and unit testing
by Laurent_R (Canon) on Feb 02, 2014 at 23:52 UTC |
Back to
Meditations