The following benchmark might be interesting:
#!/usr/bin/perl use strict; use warnings; use Fcntl qw /:seek/; use Benchmark qw /timethese cmpthese/; my $lines = shift || 50_000; my $file = "/tmp/big"; # First create a big data file. open my $fh => "> $file" or die "open: $!"; foreach (1 .. $lines) { foreach my $i (1 .. 3) { my $r = int rand 3; print $fh "abcdef" if $r == 0; print $fh "123456" if $r == 1; print $fh "<[{}]>" if $r == 2; } print $fh "\n"; } close $fh or die "close: $!"; my $words = "/tmp/words"; my $digits = "/tmp/digits"; my $punct = "/tmp/punct"; my @array = ([$words => '[a-z]'], [$digits => '[0-9]'], [$punct => '[^a-z0-9]']); sub many { foreach my $entry (@array) { open my $fh => ">", $entry -> [0] . ".m" or die "open: $!"; close $fh or die "close: $!"; } open my $fh => $file or die "open: $!"; while (<$fh>) { foreach my $entry (@array) { my ($f, $r) = @$entry; if (/$r/) { open my $fh1 => ">> $f.m" or die "open: $!"; print $fh1 $_; close $fh1 or die "close: $!"; } } } } sub one { open my $fh => $file or die "open: $!"; foreach my $entry (@array) { my ($f, $r) = @$entry; open my $fh1 => "> $f.o" or die "open: $!"; seek $fh => 0, SEEK_SET or die "seek: $!"; while (<$fh>) { print $fh1 $_ if /$r/ } close $fh1 or die "close: $!"; } } cmpthese -60 => { one => \&one, many => \&many, }; unlink $file or warn $!; unlink map {my $s = $_ -> [0]; ("$s.m", "$s.o")} @array; __END__ s/iter many one many 5.74 -- -95% one 0.267 2045% --

Going through the file repeatedly, and printing out the files one by one is a big winner.

Abigail


In reply to Re: Speed of opening and closing a file 1000s times by Abigail-II
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.