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.


In reply to Re: Cache Subroutine Return Value by Roger
in thread Cache Subroutine Return Value by souravdas

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.