Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture the output of Perl's 'system()'

Tags:

shell

perl

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.

like image 404
Dagang Avatar asked Jul 17 '12 01:07

Dagang


People also ask

How do I record a system output in Perl?

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.

How do I print a Perl command?

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.

How do I redirect output to a file in Perl script?

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.

How do I capture stderr in Perl?

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).


1 Answers

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.

like image 62
Zaid Avatar answered Sep 28 '22 05:09

Zaid