Beefy Boxes and Bandwidth Generously Provided by pair Networks RobOMonk
We don't bite newbies here... much
 
PerlMonks  

Re: Best way to read line x from a file

by davido (Cardinal)
on Mar 29, 2004 at 11:09 UTC ( [id://340653]=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 Best way to read line x from a file

my $line2 = (<FILE>)[9];

Your method evaluates <FILE> in list context, resulting in a file slurp. Then you index into only one line, and let the rest of the slurp fall into the bit-bucket.

I agree with Corion that Tie::File is a great solution.

But I couldn't leave well enough alone, and had to come up with yet another way to do it. This solution still reads through the file up until it gets to the desired line. There's no way around that unless your lines are fixed-length.:

my $linenum = 10; while ( my $line = <FILE>) { next unless $. == $linenum; # Process the one line here... last; # No need to continue. }

I hadn't seen anyone using $. yet. See perlvar.

Update:Added last; to the loop. Thanks for the reminder.


Dave

Replies are listed 'Best First'.
Re: Re: Best way to read line x from a file
by TomDLux (Vicar) on Mar 29, 2004 at 11:50 UTC

    Don't forget to make sure that "Procecss the one line..." includes the command last, to exit the loop, otherwise you simply have an expanded version of slurp.

    --
    TTTATCGGTCGTTATATAGATGTTTGCA

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://340653]
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.