http://www.perlmonks.org?node_id=991499

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

Monks monks monks,

I want to send BOTH STOUT and STDERR to my output.txt file. I know it should be simple, but for some reason I'm getting the error but not the other output. what is a good way to fix get it working?

#!/usr/local/bin/perl use warnings; use strict; my $input = shift; my $output = "/home/me/output.txt"; open (MYFILE, "$input"); while (<MYFILE>) { chomp; system("/home/me/ipinfo.pl $_ >$output 2>&1"); } close (MYFILE);

Replies are listed 'Best First'.
Re: BOTH STOUT and STDERR to same file.
by davido (Cardinal) on Sep 03, 2012 at 19:13 UTC

    I've mostly stopped bothering with trying to deal with shell redirection and the portability issues it raises. Capture::Tiny abstracts the details away and lets me get on with my work. Here's the module's decription:

    Capture::Tiny provides a simple, portable way to capture almost anything sent to STDOUT or STDERR, regardless of whether it comes from Perl, from XS code or from an external program. Optionally, output can be teed so that it is captured while being passed through to the original filehandles. Yes, it even works on Windows (usually). Stop guessing which of a dozen capturing modules to use in any particular situation and just use this one.

    The capture_merged function should give you all the ammunition you need.

    use strict; use warnings; use Capture::Tiny qw( capture_merged ); my $input = shift; my $output = '/home/me/output.txt'; my $run = '/home/me/ipinfo.pl'; open my $infh, '<', $input or die $!; open my $ofh, '>', $output or die $!; while( <$infh> ) { chomp; my( $captured, @results ) = capture_merged { system $run, $_ }; print $ofh $captured; } close $ofh or die $!; close $infh;

    Dave

Re: BOTH STOUT and STDERR to same file.
by aitap (Curate) on Sep 03, 2012 at 19:02 UTC
    system("/home/me/ipinfo.pl $_ >$output 2>&1");
    It is very unsafe (imagine somebody writing "; rm -rf /*" in the input file). Try using IPC::Run, which does all redirections itself.
    Sorry if my advice was wrong.
Re: BOTH STOUT and STDERR to same file.
by remiah (Hermit) on Sep 03, 2012 at 20:01 UTC
    system("/home/me/ipinfo.pl $_ >$output 2>&1");
    This will overwrite output file in while loop.
    What if you append the output?
    system("/home/me/ipinfo.pl $_ >> $output 2>&1");

      All I needed was to append instead of re-write my lines. Thanks for the help :).

Re: BOTH STOUT and STDERR to same file.
by Anonymous Monk on Sep 04, 2012 at 00:39 UTC
Re: BOTH STOUT and STDERR to same file.
by cheekuperl (Monk) on Sep 04, 2012 at 02:50 UTC