I was reading HOP and it got me thinking about inline caching methods. Assuming the no-false-values constraint is not a problem, there's an easy and efficient way to add caching
to a sub that returns a scalar (replace the join as needed):
my %foo_cache;
sub foo {
$foo_cache{join ",", @_} ||= do {
... rest of sub goes here
}
}
(If you have it enabled, //= is even better.)
But what about when the function generates a list? Easy enough:
my %foo_cache;
sub foo {
@{$foo_cache{join ",", @_} ||= [ do {
... rest of sub goes here
}]}
}
But that changes the result in scalar context if an actual list is returned. The fix is a little expensive:
my %foo_cache;
sub foo {
return @$_[0..$#$_] for $foo_cache{join ",", @_} ||= [ do {
... rest of sub goes here
}]
}
Can anybody suggest a less expensive alternative? Pity there's no
list keyword.