Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I am currently into writing an application in perl which operates on input Verilog HDL files. I need to constantly move forward and backward while keeping a track of the signal names. I am not sure how to move backward after seeking to a byte position.

Also, I observe that seeking to a byte position resets the line numbering. Is there a way in which I can get actual line number after seeking to a given byte position.

Replies are listed 'Best First'.
Re: Back Navigation In A File
by Abigail-II (Bishop) on Jul 21, 2003 at 11:08 UTC
    You should note that the number of the current line is kept track off because Perl increments a counter each time it reads a line. Perl does that by basically looking at each byte of the input and when it has found the end of the line (what's in $/), it has read a line, and the counter can be incremented.

    But when you seek to a certain position, Perl does not look at the bytes before the position you seek to (otherwise, seeking wouldn't be fast), so it has no way of knowing which line it is. Don't forget that on many systems, including Unix and Windows systems, files are just streams of bytes. The OS has no concept of lines.

    If you must know the line numbers, what you can do is first you read the entire file, line-by-line, keeping track on which byte each line starts. You then have an index. Given the index, you can binary search to find the line number, given a position you seeked to.

    Abigail

Re: Back Navigation In A File
by BrowserUk (Patriarch) on Jul 21, 2003 at 14:33 UTC

    Use Tie::File.


    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong." -Richard Buckminster Fuller

Re: Back Navigation In A File
by nega (Scribe) on Jul 21, 2003 at 15:14 UTC
    While it's not what your looking for (since you're reading by bytes) File::ReadBackwards might help someone who only needs to read by lines.