Perl – Capture the output of Perl’s ‘system()’

perlshell

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.

Best Answer

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.