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

Fellow monks,

I am experiencing some inconsistent behavior with tied filehandles between perl 5.6.1 and 5.8.3 (ActiveState Perl).
Background Info: I'm looking to carefully insert a few lines of perl code into a bunch of existing scripts to make sure everything printed to the 'screen' (stdout, stderr, stdin) also gets recorded in a logfile.
Constraints: I'm hoping to avoid having to change a zillion 'print' statements to do this. I have to be careful not to depend on CPAN packages as this will introduce additional administrative overhead. I'm hoping to have this working on both 5.6 and 5.8.
The Problem: In 5.6.1 output to the screen does not seem to come out in the expected 'sequence' and nothing is printed to the logfile after the tie.

Is this a bug in 5.6? Is there a better way to write this that may sidestep whatever issue there might be?

Code:
#! perl -w use strict; $| = 1; print "$0 | start | " . localtime() . "\n"; print STDOUT "This is STDOUT\n"; print "Now ask for STDIN: "; my $input = <STDIN>; chomp($input); print "Input : " . $input . "\n"; print "Now let's mess with things...\n"; my $logfile = "./logfile.log"; open( STDOUT_TOO, ">&STDOUT" ) or die "Cannot dup STDOUT handle to STD +OUT_TOO: $!"; open( LOGFILE, ">$logfile" ) or die "Cannot open $logfile for output: +$!"; tie *STDOUT, 'MyMultiplex', \*STDOUT_TOO, \*LOGFILE; print "And let's see the effects...\n"; print STDOUT "This is STDOUT\n"; print "Now ask for STDIN: "; $input = <STDIN>; chomp($input); print "Input : " . $input . "\n"; print "$0 | end | " . localtime() . "\n"; package MyMultiplex; sub TIEHANDLE { my $obj = shift; bless [ @_ ], $obj; } sub PRINT { my $self = shift; print $_ $_[0] for @$self; }


Output:
- 5.6
H:\Developer\deploysystem\src>perl scratch.pl scratch.pl | start | Wed Jun 30 12:13:45 2004 This is STDOUT Now ask for STDIN: this is 5.6 Input : this is 5.6 Now let's mess with things... 'mess with things' printed out of sequence And let's see the effects... This is STDOUT Now ask for STDIN: Input : 'mess with things' printed out of sequence scratch.pl | end | Wed Jun 30 12:14:06 2004


- 5.8
H:\Developer\deploysystem\src>perl scratch.pl scratch.pl | start | Wed Jun 30 12:15:07 2004 This is STDOUT Now ask for STDIN: this is 5.8 Input : this is 5.8 Now let's mess with things... And let's see the effects... This is STDOUT Now ask for STDIN: it works on my machine! Input : it works on my machine! scratch.pl | end | Wed Jun 30 12:15:18 2004

edit: added another <readmore>

Replies are listed 'Best First'.
Re: tied filehandle behaviour 5.6 vs 5.8
by jdalbec (Deacon) on Jul 02, 2004 at 02:44 UTC
    You've unbuffered STDOUT, but you also need to unbuffer STDOUT_TOO and LOGFILE.
      Durr... of course! Thanks for catching that.