Question

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?

Était-ce utile?

La solution

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)

Autres conseils

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).

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top