my %cache; sub first_line { my ($filename) = @_; unless (exists $cache{$filename}) { open( my $fh, $filename ) or die "Cannot open '$filename': $!\ +n"; $cache{$filename} = <$fh>; } return $cache{$filename}; }
Instead of checking for the existence of the cached value, I check for the non-existence of the cached value. If it doesn't exist, I populate it. That way, I always return the cached value and the logic is slightly easier to work with.
On a sidenote, I would look at Memoize. It's a module that's built to do exactly what you're trying to do.
Update: Changed return to die as per jdporter's comment that reading an empty file gives back undef.
------
We are the carpenters and bricklayers of the Information Age.
Then there are Damian modules.... *sigh* ... that's not about being less-lazy -- that's about being on some really good drugs -- you know, there is no spoon. - flyingmoose
I shouldn't have to say this, but any code, unless otherwise stated, is untested
In reply to Re: Cache Subroutine Return Value
by dragonchild
in thread Cache Subroutine Return Value
by souravdas
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |