my %cache; my ($ncalls, $nhits); sub first_line { my ($filename) = @_; $ncalls++; if (exists $cache{$filename}) { $nhits++; } else { open( my $fh, $filename ) or die "Cannot open '$filename': $!\n"; $cache{$filename} = <$fh>; } return $cache{$filename}; } END { print "first_line returned cached value $nhits times in $ncalls calls\n" }