0

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?

1
  • 3
    You can "return" strings through STDOUT from which you can create an array in the calling process. Commented May 6, 2014 at 20:41

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

3 Comments

Will the STDOUT string array will be appended to the 0/1 exit return codes?
@KingsInnerSoul: No, it won't. The return code is just a small integer. Any data written to STDOUT is separate.
@KingsInnerSoul The exit return code is separate. What you're doing is outputting to STDOUT, and then using the output of the command to set your environment variable. The (...) runs the command and replaces $(...)with STDOUT of that command. You can still look at $? to see the actual return exit code.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.