I need to run a shell command with system() in Perl. For example,
system('ls')
The system call will print to STDOUT, but I want to capture the output into a variable so that I can do future processing with my Perl code.
system() runs a command and returns exit status information (as a 16 bit value: the low 7 bits are the signal the process died from, if any, and the high 8 bits are the actual exit value). Backticks (``) run a command and return what it sent to STDOUT.
open(F, "ls | tee /dev/tty |"); while (<F>) { print length($_), "\n"; } close(F); This will both print out the files in the current directory (as a consequence of tee /dev/tty ) and also print out the length of each filename read.
Redirect STDOUT using a filehandle As with select, this will have a global affect on the Perl program. use feature qw/say/; use autodie; # copy STDOUT to another filehandle open (my $STDOLD, '>&', STDOUT); # redirect STDOUT to log. txt open (STDOUT, '>>', 'log. txt'); say 'This should be logged.
You can use Capture::Tiny to capture stdout, stderr or both merged. Show activity on this post. I'm personally a fan of the core module IPC::Open3, though the answer with 2>&1 will get both stderr and stdout in the same stream (and usually good enough).
That's what backticks are for. From perldoc perlfaq8
:
Why can't I get the output of a command with
system()
?You're confusing the purpose of
system()
and backticks (``).system()
runs a command and returns exit status information (as a 16 bit value: the low 7 bits are the signal the process died from, if any, and the high 8 bits are the actual exit value). Backticks (``) run a command and return what it sent to STDOUT.my $exit_status = system("mail-users"); my $output_string = `ls`;
See perldoc perlop
for more details.
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