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

Hello Monks

This is a bit of a shot in the dark, but I was wondering if any of you knew how to overload a print statement to print to both a file and the screen?
Right now I am duplicating the print statements, ie print "hi\n"; print LOG "hi\n"; and that not only looks ugly, it is really bothersome for making changes to much of anything.

I could just run it | tee but I was really hoping for a nice pretty idiot proof way of doing it in perl that lets code changes be less frustrating.
Ideas?


jcpunk
all code is tested, and doesn't work so there :p (varient on common PM sig for my own ammusment)

Replies are listed 'Best First'.
Re: Print to the screen and a log at the same time?
by philcrow (Priest) on May 09, 2006 at 15:26 UTC
Re: Print to the screen and a log at the same time?
by blazar (Canon) on May 09, 2006 at 15:26 UTC
Re: Print to the screen and a log at the same time?
by punkish (Priest) on May 09, 2006 at 15:28 UTC
    sub _print { my ($msg) = @_; print $msg, "\n"; print LOG $msg, "\n"; } _print("hello"); _print("world");
    --

    when small people start casting long shadows, it is time to go to bed

      Why not

      sub _print { print $msg, @_; print LOG $msg, @_; } _print("hello"); _print("world");

      That way, you can print lists, and $, and $\ will be obeyed. OTOH, the simplest solution is probably the following:

      use IO::Tee (); my $fh_out = IO::Tee->new(\*STDOUT, \*LOG); select($fh_out); print("hello"); print("world");

      But there are problems with using select.

Re: Print to the screen and a log at the same time?
by ruzam (Curate) on May 09, 2006 at 16:13 UTC
    After you open LOG but before you print anything, add this code:
    if (!(my $pid = open(STDOUT, "|-"))) { die "fork failed: $!" unless defined $pid; while (<STDIN>) { print $_; print LOG $_; } exit; }
    This will fork a child process that will capture everything sent to STDOUT. The print statements appear to the child as STDIN. What you do with it is up to your code.
Re: Print to the screen and a log at the same time?
by QM (Parson) on May 09, 2006 at 23:05 UTC
    Do you have tee available on your system? Not everything has to be in Perl.

    -QM
    --
    Quantum Mechanics: The dreams stuff is made of