perl - using backticks instead of system()

22,141

Solution 1

To go through the shell in order to move data from one perl script to another is not the best solution. You should know that backticks or qx() captures whatever is printed to STDOUT. Using exit ($var) from the other script is unlikely to be captured properly. You would need print $var. But don't do that.

Instead, make the other script into a module and use the subroutine directly. This is a simplistic example:

In bar.pm:

use strict;
use warnings;

package bar;  # declare our package

sub fooz {             # <--- Our target subroutine
    my $in = shift;    # passing the input
    return $in * 5;    # return value
}
1; # return value must be true

In main.pl:

use strict;
use warnings;
use bar;   # bar.pm must be in one path in @INC

my $foo = bar::fooz(12);  # calling fooz from our other perl script
print "Foo is $foo\n";

There is a lot more to learn, and I suggest you read up on the documentation.

Solution 2

You want IPC::System::Simple's capturex.

use IPC::System::Simple qw( capturex );
my $output = capturex("perl", $path, $val1, $val2, @myarray);

It even handles errors for you.

Solution 3

The backticks simply work like a direct invocation one would make in a shell:

you@somewhere:~$ ./script.pl --key=value

Is basically the same as

my $returnval = `./script.pl --key=value`;

Solution 4

For invoking other programs passing arguments and capturing output at the same time, I'm a big fan of IPC::Run:

use IPC::Run 'run';

my $exitcode = run [ $command, @args ], ">", \my $output;

# $exitcode contains the exit status and
# $output contains the command's STDOUT data

Solution 5

Does this not do what you want?

my $returnval = `$path $val1 $val2 @myarray`;

@Quentin however adds this useful advice: If the value you want to pass is foo "bar then in shell you would have to do something like "foo \"bar". Using extra arguments to system will take card of that for you. Using backticks won't; you need to construct the shell command you want manually.

Share:
22,141
Tyzak
Author by

Tyzak

Student in Germany

Updated on June 04, 2020

Comments

  • Tyzak
    Tyzak almost 4 years

    I have a perl script that calls an other perl script by using system()

    it's like:

    my $returnval= system("perl", $path,$val1, $val2,@myarray);
    

    Because system() returns only the exit status but I want the script's output I want to use backticks.

    I tried something like that:

    my $returnval = `$path`;
    

    how can I add the parameters the script should receive?

    how should the other perl script's return code looks like? At the moment it's like

    exit ($myreturnedvalue);
    

    (how) Is it possible to return multiple values?