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

Re: Best way to read line x from a file

by arden (Curate)
on Mar 29, 2004 at 15:31 UTC ( [id://340638]=note: print w/replies, xml ) Need Help??


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

Unless your lines are all the same length, I think the best way is probably that which you've chosen. If, however, your lines are all the same length, you could use seek();.

Here is how I read in a specific line from a file if I am only interested in the one bit of a file.

$. = 0; do { $LINE = <FILE> } until $. == $DESIRED_LINE_NUMBER || eof;
Now, if you're going to potentially bounce around within the file (say, look at line 5000, then line 20, then line 42, etc), there are other strategies, but since I don't think that's what you're looking for, we won't go there right yet. . .

- - arden.
arden is more of an orangutan than a monkee

Replies are listed 'Best First'.
Re: Re: Best way to read line x from a file
by Melly (Chaplain) on Mar 29, 2004 at 15:35 UTC

    Is it wasteful? - i.e. does such notation force perl to read in the whole file, or does it just read in the lines up to line x, or does it (we can but hope) somehow *just* read in line x?

    Tom Melly, tom@tomandlu.co.uk
      No, seek() is not wasteful, however it doesn't really understand the concept of a line either. Seek basically blitzes its way to the location requested, so any future reads start from that location. You can also use seek to go backwards in a file too. But again, it doesn't work on the principle of "lines", instead it works on "byte offsets". That's why in your case it would only work if every line is of the same length.

      - - arden.
      arden is more of an orangutan than a monkee

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (6)
As of 2024-04-18 06:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found