I would suggest neither solution. Why not simply keep all the files open? Or if there are many, you could keep a cache of open files which closes files based upon how long ago they were used (an LRU cache) or some other kind of heuristic that can determine the likelihood the file will be used again soon (such as frequency of use). For example:

my %file_cache; sub open_file($) { my $filename = shift; return $file_cache{$filename} || (open $file_cache{$filename}, ">>$filename" or die "blah blah $!"); } while (<FILE> { foreach my $n (@natures) { if ($_ =~ /%n/) { my $out = open_file "$n.txt"; print $out $n; } } }

If there is the potential for many files, delete an entry from the cache managed by open_file when the given $filename isn't currently open and the cache is "full".

This way you don't have to open files over and over again quite so often--we hope--and you don't have to perform reiterations.


In reply to Re: Speed of opening and closing a file 1000s times by hanenkamp
in thread Speed of opening and closing a file 1000s times by seaver

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.