in reply to seek() command on STDOUT

Does seek() not work on STDOUT

Short answer:No. Longer answer: No. How could it?


Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
RIP an inspiration; A true Folk's Guy

Replies are listed 'Best First'.
Re^2: seek() command on STDOUT
by afoken (Chancellor) on Apr 30, 2010 at 05:47 UTC

    There is nothing special about STDOUT, it's just another file handle. seek() does work on STDOUT if STDOUT is seekable, e.g. a plain file. But (pseudo) TTYs usually aren't seekable, at least not for writing, so seek() doesn't work when STDOUT is not redirected.

    #!/usr/bin/perl -w use strict; seek(STDOUT,14,0); print "Now I'm there\n"; seek(STDOUT,0,0); print "Now I'm here\n";

    Run without redirection (perl foo.pl), and you get:

    Now I'm there Now I'm here

    The seek()s simply fail, and because the code does not check for errors, seek() seems to be a dummy for STDOUT.

    Run again, redirecting to a file (perl foo.pl > foo.txt; cat foo.txt), and the file contains:

    Now I'm here Now I'm there

    Now let's play safe and add some error checking:

    #!/usr/bin/perl -w use strict; seek(STDOUT,14,0) or warn $!; print "Now I'm there\n"; seek(STDOUT,0,0) or warn $!; print "Now I'm here\n";

    Run again, without redirection:

    Illegal seek at foo.pl line 4. Now I'm there Illegal seek at foo.pl line 6. Now I'm here

    So, seek() is not a dummy, it simply fails, because the TTY does not allow seek() for write access.

    Redirecting to a file, as above, works without any warnings:

    Now I'm here Now I'm there

    Alexander

    --
    Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)
      There is nothing special about STDOUT, it's just another file handle.

      Yes there is. By default, its pre-opened--and in most sensible uses--is connected to either the console or a pipe. Both non-seekable devices.

      Yes, the OP could re-open STDOUT to a seekable device, (he could also overload '+' to do subtraction), but if he was doing that, he wouldn't have a problem.