1

Possible Duplicate:
How can I store Perl's system function output to a variable?

I have tried to run a shell command in my Perl script. An example is like below:

system ("ls -al");

The result is well printed on Unix.

Is there a way to return the result to $string in my Perl script instead of returning the result on Unix?

I do not want the result to be printed on my Unix.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Steven
  • 315
  • 3
  • 5
  • 6
  • This is well covered in the Perl manpage for back tick operator at http://perldoc.perl.org/perlop.html#%60STRING%60 – Alex Brown Sep 05 '12 at 03:59

1 Answers1

14

Use the backticks:

$string = `ls -al`;

The 'qx' delimiter is a synonym for this:

$string = qx{ls -al};

This is documented here in the perlop man page.

Alternately, you can use open with '|' like so:

open my $filehandle, "ls -al|" or die "Open failed!\n";
while(<$filehandle>) {do_something($_);}
close $filehandle;

In this case, you're opening a filehandle to a pipe attached to the command's output (basically treating the output as a file). This is handy if the command takes a long time or produces more output than you want to store in memory at a time. This is documented in the Perl open manual.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Chris Reuter
  • 1,458
  • 10
  • 8
  • 2
    $var = qx(ls -l 2>&1) will also give you the errors in $var....by default qx does not capture stderr. You should also examine the value of $@, which is the exit code of the program (non-zero means it had a problem) – Tony K. Sep 05 '12 at 06:31