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

I am reading a text file from STDIN, and I'd like to optimize my program by seeking back in the input sometimes. However, the input can come from a pipe or even directly from terminal, in which case seeking back is not possible. I'd like my code to work in this case too, so I want to determine whether a handle can be seeked back.

I have two ideas on how to do this, but I'm not quite sure they'll always work.

Firstly

if (sysseek STDIN, 0, 1) { # run the optimized code } else { # run the slow code that stores data in memory instead of seeking +back in the file }
but linux manpage for lseek(2) reports that on some non-linux systems lseek can succeed on terminal devices.

The second is

if (-f STDIN || -b STDIN) { # fast code } else { # slow code }
but I'm not sure whether I can trust this either.

Please advice me, wise monks, on the proper way to find out whether it is possible to seek a handle back.

Replies are listed 'Best First'.
Re: Find out if handle is seekable
by Ben Win Lue (Friar) on Apr 08, 2005 at 08:33 UTC
     Posix::isatty (in words: is_a_tty) could be worth a look. It returns true, if the filehandle is associated with a terminal.

      Isatty won't return true on a pipe or a named pipe (fifo) or a socket, so it's not what I want. By the way, isn't the -t filetest operator the same as isatty?