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.


In reply to Find out if handle is seekable by ambrus

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.