Question

I need to know how is possible return values of Perl file from other Perl file.

In my first file i call to the second file with sentence similar to:

$variable = qx( perl file2.pl --param1 $p1 --param2 $p2);

I have tried with exit and return to get this data but is not possible.

Any idea?

Was it helpful?

Solution 2

In file2.pl, you must print something to STDOUT. For example:

print "abc\n";

OTHER TIPS

Processes are no subroutines.

Communication between processes (“IPC”) is mostly done via normal file handles. Such file handles can specifically be

  • STDIN and STDOUT,
  • pipes that are set up by the parent process, these are then shared by the child,
  • sockets

Every process also has an exit code. This code is zero for success, and non-zero to indicate a failure. The code can be any integer in the range 0–255. The exit code can be set via the exit function, e.g. exit(1), and is also set by die.

Using STDIN and STDOUT is the normal mode of operation for command line programs that follow the Unix philosophy. This allows them to be chained with pipes to more complex programs, e.g.

cat a b c | grep foo | sort >out

Such a tool can be implemented in Perl by reading from the ARGV or STDIN file handle, and printing to STDOUT:

while (<>) {
  # do something with $_
  print $output;
}

Another program can then feed data to that script, and read it from the STDOUT. We can use open to treat the output as a regular file handle:

use autodie;
open my $tool, "-|", "perl", "somescript.pl", "input-data"; # notice -| open mode
while (<$tool>) {
  ...
}
close $tool;

When you want all the output in one variable (scalar or array), you can use qx as a shortcut: my $tool_output = qx/perl somescript.pl input-data/, but this has two disadvantages: One, a shell process is executed to parse the command (shell escaping problems, inefficiency). Two, the output is available only when the command has finished. Using open on the other hand allows you to do parallel computations.

print is the solution.

Sorry for my idiot question!

#

 $variable = system( perl file2.pl --param1 $p1 --param2 $p2);
 #$variable has return value of perl file2.pl ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top