[Chapter 3] 3.2.132 seek
Author: Larry Wall, Tom Christiansen & Randal L. Schwartz
Date: 1999-07-02T01:53:40Z

#

| Chapter 3 Functions |

### 3.2.132 seek

    seek FILEHANDLE, OFFSET, WHENCE

This function positions the file pointer for `FILEHANDLE`, just like the fseek(3) call of standard I/O. The first position in a file is at offset 0, not offset 1, and offsets refer to byte positions, not line numbers. (In general, since line lengths vary, it's not possible to access a particular line number without examining the whole file up to that line number, unless all your lines are known to be of a particular length, or you've built an index that translates line numbers into byte offsets.) `FILEHANDLE` may be an expression whose value gives the name of the filehandle or a reference to a filehandle object. The function returns 1 upon success, 0 otherwise. For handiness, the function can calculate offsets from various file positions for you. The value of `WHENCE` specifies which file position your `OFFSET` is relative to: `0`, the beginning of the file; `1`, the current position in the file; or `2`, the end of the file. `OFFSET` may be negative for a `WHENCE` of `1` or `2`.

One interesting use for this function is to allow you to follow growing files, like this:

    for (;;) {
        while (<LOG>) {
            ...           # Process file.
        }
        sleep 15;
        seek LOG,0,1;      # Reset end-of-file error.
    }

The final seek clears the end-of-file error without moving the pointer. If that doesn't work (depending on your C library's standard I/O implementation), then you may need something more like this:

    for (;;) {
        for ($curpos = tell FILE; $_ = <FILE>; $curpos = tell FILE) {
            # search for some stuff and put it into files
        }
        sleep $for_a_while;
        seek FILE, $curpos, 0;
    }

Similar strategies could be used to remember the seek addresses of each line in an array.

3.2.131 scalar |  | 3.2.133 seekdir