in reply to Cache Subroutine Return Value

I'd say that the code is not correct (missing a ; on the if exists line) and not clean enough because it leaves a lot of open file handles. Although that might be correct if you intend to keep the file open. When you have too many files in your cache, you will eventually run out of file handles and your script will fail. Throw in a close FILE before the return to free up the file handle.

I would recommend using the IO::File module whenever doing file IO.

my %cache; sub first_line { my $filename = shift; return $cache{$filename} if exists $cache{$filename}; my $f = new IO::File $filename, "r" or die "file not found"; my $line = <$f>; $cache{$filename} = $line; return $line; }

Note that I did not explicitly close the file handle, because when the sub finishes, the object $f will get out of scope and automatically disposed of, which invokes the destructor of the file object, which closes the file implicitly. This could be quite handy when working with files, because you don't have to track the files that you have openned and you don't have to close them explicitly.