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.
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);
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With