I am calling a perl file from shell and I want it to return few variables. I know I can use the exit $code to exit from Perl, but I want to get an array with unique values. When I tried to add return @array it complained on me. Any ideas?
-
3You can "return" strings through STDOUT from which you can create an array in the calling process.ikegami– ikegami2014-05-06 20:41:13 +00:00Commented May 6, 2014 at 20:41
2 Answers
You can't return anything other than a short integer as a return code. The idea is that the return code is 0 if the program works, and non-zero otherwise.
You can return a string, then allow your shell script to parse that string as an array.
For example, if your @array = qw(one two three four five), simply print that as the only line on STDOUT. If you want to say anything else, print that to STDERR:
use strict;
use warnings;
use feature qw(say);
my @array = qw(one two three four five);
say STDERR "I'm about to print out the final array"; # Doesn't print to STDOUT...
say "(" . join ( " ", @array ) . ")"; # Prints to STDOUT
This program will print out:
(one two three four five)
Now in your shell script, you can do this:
declare -a shell_array=$(my_perl_prog.pl)
3 Comments
STDOUT is separate.(...) runs the command and replaces $(...)with STDOUT of that command. You can still look at $? to see the actual return exit code.exit always outputs a number and that's a matter of the exit status of a program which is rather narrow in definition. In general practice, you exit with 0 if everything went as planned and with some other number to signify an error or unexpected result.
return can pass anything to a calling method, but the main part of the program is has no calling method, so it has nothing to return to. That's the cause of your syntax error. You can export information from your process by writing to a file handle (including stdout by using print), opening files, or writing to sockets (network traffic).