Beefy Boxes and Bandwidth Generously Provided by pair Networks Frank
laziness, impatience, and hubris
 
PerlMonks  

Re: Best way to read line x from a file

by arden (Curate)
on Mar 29, 2004 at 10:31 UTC ( [id://340638]=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

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 10: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
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.