Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Best way to read line x from a file

by Corion (Patriarch)
on Mar 29, 2004 at 15:34 UTC ( [id://340640]=note: print w/replies, xml ) Need Help??


in reply to Best way to read line x from a file

I think that Tie::File is the best compromise between speed and simplicity for such tasks.

The fastest way would be a loop like the following, assuming that the line indicated by $line_no will start in the first half of the file:

<FILE> while ($line_no--); my $line2 = <FILE>;

as then, Perl and the OS will do some buffering for you, and you don't read the whole file for nothing.

If your file size is smaller than one sector, the OS (and the HD) will read it into memory anyway, and it might be faster to slurp it into memory and use a crafted regular expression against it:

use File::Slurp qw(slurp); my $f = slurp $filename; my $line2 = $1 if (m!\n{$line_no-1}([^\n]*)\n!sm);

So in the end, you will have to benchmark a lot.

Replies are listed 'Best First'.
Re2: Best way to read line x from a file
by Hofmator (Curate) on Mar 30, 2004 at 12:17 UTC
    A couple of small things went wrong in your 2nd example.
    • slurp is spelled read_file, at least in the newest CPAN version 9999.04.
    • The regex is matching against $_, not $f.
    • The regex is not working in multiple ways :). {$line_no-1} evaluates to e.g. {10-1} which looks for the literal string '{10-1}'. Even if this worked, it would be looking for consecutive newlines, so consecutive empty lines. And there are more mistakes ...

    The correct version should be something like this:

    use File::Slurp; my $f = read_file $filename; my $line2 = $1 if ($f =~ m!\A(?:.*\n){@{[$line_no-1]}}(.*)\n!m);
    ... but I wouldn't recommend it.

    And for the sake of completeness, here the solution spelled out with Tie::File which lots of people mentioned already.

    use Tie::File; tie my @file, 'Tie::File', $filename or die "Couldn't tie '$filename': $!"; my $line2 = $file[9];

    -- Hofmator

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://340640]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (4)
As of 2024-04-20 00:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found