Problem using "system" command in perl

Hello!!!

I'm trying to pass the output from bash command to perl variable in a perl script, and I used the "system" command to execute the bash statment and pass the result to perl string variable, in this perl script I used a variable $file that store data for using it as a regular expression.
Here I show you some part of the script:

$output = system "find /path/ | grep $file | sed 's/ /\ /g'";
system "evince $output";
print $output;

Output: in the screen the script prints 0

The result I want obtain is the path found by grep allocated in the perl variable $output.

the only I have obtained is a zero allocated in $output perl variable. I have tried the bash one-line script in linux terminal and it works very fine because it shows me the correct result I want.

I would appreciate if you can help me to solve this

You have assigned the exit status of the Unix command to the Perl variable $output. Since the command was successful, its exit status was 0 and so it gets assigned to $output.

If you want to assign the output of the Unix command to a Perl variable, then use backticks (``) or qx// function.

$
$
$ # Run a command first and check its output
$
$ ls f1
f1
$
$ # Now run this command from within Perl, and using "system" function
$
$ perl -le 'system ("ls f1")'
f1
$
$ # Try to assign the command output to a Perl variable
$
$ perl -le '$x = system ("ls f1"); print "\$x = $x"'
f1
$x = 0
$
$
$ # The first line is the actual output; the second line is the value of $x
$ # which in turn is the exit status of the command
$
$ # Use backticks to assign the output in Perl
$
$ perl -le '$x = `ls f1`; print "\$x = $x"'
$x = f1
 
$
$
$ # You can also use qx// function
$
$ perl -le '$x = qx/ls f1/; print "\$x = $x"'
$x = f1
 
$
$

tyler_durden

1 Like

Thank you a lot. This was really didactic.