Beefy Boxes and Bandwidth Generously Provided by pair Networks vroom
Perl Monk, Perl Meditation
 
PerlMonks  

Re2: Best way to read line x from a file

by Hofmator (Curate)
on Mar 30, 2004 at 07:17 UTC ( [id://340933]=note: print w/replies, xml ) Need Help??

This is an archived low-energy page for bots and other anonmyous visitors. Please sign up if you are a human and want to interact.


in reply to Re: Best way to read line x from a file
in thread Best way to read line x from a file

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://340933]
help
Sections?
Information?
Find Nodes?
Leftovers?
    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.