is there a way to tell/force the perl compiler to cache values inside a loop?
of course I can create my values outside of the loop, but with increasing complexity of code, I find it more readable to create the values inside of the loop, although they don’t change
for example:
my $key = shift;
my @input = @_;
my %output;
foreach(@input) {
my $output_tmp = specialOperation($_);
...
my $key_tmp = constantOperation($key);
my $specialKey = specialOperation2($_,$key_tmp);
...
$output{$specialKey} = $tmp;
}
$keyTmp has the same value in every iteration and I would like the compiler to cache it
in a regex you can use the o-flag
is there something similar, e.g. a keyword, to accomplish this?
There is not really any additional complexity introduced by altering your code as follows:
But accepting for a moment that you have a reasonable undisclosed argument for why you wouldn’t want to just do that, another possibility (if constantOperation is a pure function) is to use Memoize.
The latter doesn’t avoid the repeated function call, but does cause caching within the function called constantOperation, so subsequent calls with a previously used parameter will provide a cached result.
Going back to the first example, you could just move the “my” declaration out of the loop, and then within the loop use something like this:
$key_tmp //= constantOperation($key);. Here’s how that might look:And this being Perl, there’s always one more way to do it. Enable the ‘state’ feature, and change
my $key_tmptostate $key_tmp. Here’s how that might look: