in reply to FILE operation in PERL

Now if I need to go back to a particular line say line number 30 ...how do I do it if I have already passed this line.

There are two approaches.

  1. Read the entire file into memory. (E.g., as an array of lines.) You get rapid access to arbitrary lines.

    my @lines = <FILE>; will read from an open file handle into an array.

  2. If the file can't fit in memory (or you choose not to read it all in at once), use tell() to remember interesting places, and seek() to get you back there. They're covered in perlfunc.

Update: tilly pointed out that it's also possible to re-read the file. You can do that by closing and reopening the file (which assumes that the file hasn't been rewritten in the interim), or you can rewind the file handle.

Replies are listed 'Best First'.
Re: Re: FILE operation in PERL
by ramesh_nathan (Initiate) on Jul 19, 2003 at 08:16 UTC
    Thanks for your tips...It looks like now I am really close to solving the problem...Just one glitch... I have used the "tell" function to store the location of interest...and then I use the "seek" function to take me there...When I then try to read using $line=<FILE>, I am able to read the next line following the line I actually want....Can u please provide any input on this...
      When I then try to read using $line=<FILE>, I am able to read the next line following the line I actually want...

      Do the tell() before you read the line. Otherwise, as you've noticed, you're one line too late.

        I did exactly that...but even then when I initiate the $line=<file> command somehow, the cursor is moving to the next line...