in reply to Cache Subroutine Return Value

The code looks correct. On a stylistic note, I would write it slightly differently.
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

Replies are listed 'Best First'.
Re^2: Cache Subroutine Return Value
by jdporter (Paladin) on Aug 11, 2004 at 15:03 UTC
    I would make the following additional change: If the open() fails, throw an exception (die), rather than returning a value which is indistinguishable from a valid first line. (An empty string is what you'd get if the file contains 0 bytes.)
      Huh. Never knew that. It actually returns undef, not the empty string, which is what return; will send back to the caller. Updated.

      ------
      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