Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I send Perl output to a both STDOUT and a variable?

Tags:

perl

I would like to send the output from a command to both STDOUT and to a variable. I want to combine:

my $var = `some command` ;   
system( 'some command' ) ;

Tee is a step in the right direction but this sends it to a file rather than to a variable. I guess I could then read the file but it would be simpler to get it straight there.

like image 362
justintime Avatar asked Mar 11 '09 13:03

justintime


2 Answers

Does the output to both streams have be simultaneous?

If not, you could do:

my $var = 'cmd'
my $output = `$cmd`
print STDOUT $output

or for a safer version, which doesn't involve invoking a subshell, and prints to STDOUT a line at a time:

sub backtick(@)
{
    my $pid = open(KID, '-|');
    die "fork: $!" unless defined($pid);
    if ($pid) {
        my $output;
        while (<KID>) {
            print STDOUT $_;
            $output .= $_; # could be improved...
        }
        close(KID);
        return $output;
    } else {
        exec @_;
    }
}

my @cmd = ('/bin/ls', '-l');
my $output = backtick(@cmd);
like image 108
Alnitak Avatar answered Sep 28 '22 07:09

Alnitak


You want Capture::Tiny

use Capture::Tiny 'tee';
my $output = tee { system( "some command" ) };

I wrote it to replace Tee and about 20 other modules that do some sort of capturing but are flawed in one way or another.

-- xdg (aka dagolden)

like image 39
xdg Avatar answered Sep 28 '22 09:09

xdg