Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: Best way to read line x from a file

by davido (Cardinal)
on Mar 29, 2004 at 16:09 UTC ( [id://340653]=note: print w/replies, xml ) Need Help??


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 16: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
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (4)
As of 2024-04-19 23:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found