There is common pattern to cache result of heavy calculations.
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
since 5.10 there is "state" statement, making this pattern even more easy.
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?
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|