[Israel.pm] print to 2 places at the same time

Mikhael Goikhman migo at homemail.com
Tue Jun 1 09:51:38 PDT 2004

On 01 Jun 2004 19:03:07 +0200, Offer Kaye wrote:
> I'm trying to use advice from "perlfaq5" and print to 2 places at once
> (STDOUT and a file) using "tee". However, in my case I have to intercept the
> prints to the filehandle with prints just to STDOUT. Example code:
> open(OUT,"| tee foo.txt") or die "tee foo no good: $!\n";
> print OUT "foobar\n";
> print OUT "barfoo\n";
> close(OUT) or die "wtf?\n";
> The problem is, the above doesn't print:
> As you would expect. It instead prints:
> foobar
> barfoo
> This happens even of I do "$|=1;" at the beginning of the script.

Well the correct line would be:

  select OUT; $| = 1; select STDOUT; $| = 1;

But in this case it does not help either in this specific case.

> Anyone have any idea what is happening?

Well after the open line you have 2 concurrent processes writting
to the same output file handler. The result will be random, but it is
likely that the first main process wins, since it just prints directly
without waiting for the pipe input from another process.

> Anyone have any workaronds?

One trick is to add this line after your open line:

  open STDOUT, ">&", \*OUT;
  select OUT; $| = 1; select STDOUT; $| = 1;

and this line before your close line:


There are other solutions too, but maybe this one is good enough.


perl -e 'print+chr(64+hex)for+split//,d9b815c07f9b8d1e'

More information about the Perl mailing list