in reply to Re: seek() command on STDOUT
in thread seek() command on STDOUT

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". ;-)

Replies are listed 'Best First'.
Re^3: seek() command on STDOUT
by BrowserUk (Patriarch) on Apr 30, 2010 at 06:28 UTC
    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.