I don't think there's a way to do exactly what you want and
pull out X number of lines in one shot. You're better off
doing something like limitting the number of bytes you read
in at a time. I threw together a bit of code (posted
below) which reads in a certain amount of bytes, splits
that into an array, and then processes those lines. Used
with a reasonable size of bytes to read in, it seems to
consistently be about 1.5 times faster.
#!/usr/bin/perl
use Benchmark;
use strict;
timethese(10, { 'linebyline' => \&linebyline, 'chunk' => \&chunk });
sub linebyline {
open(FILE, "file");
while(<FILE>) { }
close(FILE);
}
sub chunk {
my($buf, $leftover, @lines);
open(FILE, "file");
while(read FILE, $buf, 10240) {
$buf = $leftover.$buf;
@lines = split(/\n/, $buf);
$leftover = ($buf !~ /\n$/) ? pop @lines : "";
foreach (@lines) { }
}
close(FILE);
}
Benchmark: timing 10 iterations of chunk, linebyline...
chunk: 60 wallclock secs (55.20 usr + 3.48 sys = 58.68 CPU)
linebyline: 95 wallclock secs (91.67 usr + 2.16 sys = 93.83 CPU)
These tests were run on a 25 meg file with roughly 1 million
lines in it. This code is not guaranteed to work 100%, but
I believe it is correct enough to serve benchmarking
purposes well.
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.