A function in Perl module takes 3 parameters. The value of the first parameter will determine the values of the other parameters and return them back to the caller. It is defined like this:
package MyModule;
sub MyFunction
{
my $var_0 = $_[0];
my $var_1;
my $var_2;
if ($var_0 =~ /WA/) {
$var_1 = "Olympia";
$var_2 = "Population is 53,000";
}
elsif ($var_0 =~ /OR/) {
$var_1 = "Salem";
$var_2 = "Population is 172,000";
}
$_[1] = $var_1;
$_[2] = $var_2;
return 0; # no error
}
Calling this function from the bash shell script:
VAL=`perl -I. -MMyModule -e 'print MyModule::MyFunction("WA")'`
echo $VAL
Problem: The VAL only stores the value of the last variable or $var_2.
Question: How can I retrieve the value from both $var_1 and $var_2, for use later in this bash script? ( assuming code from perl function can not be modified). Thanks for your help.
CodePudding user response:
Your function is modifying the value of its arguments #2 #3 so you may pass variables to it and print them:
perl -l -I. -MMyModule -e 'MyModule::MyFunction("WA",$a,$b); print $a; print $b;'
CodePudding user response:
You print the value returned by MyFunction
, which is 0
. So that's why 0
is assigned to $VAL
.
You should return the value instead of assigning them to the $_[1]
and $_[2]
.
package MyModule;
use Exporter qw( import );
our @EXPORT = qw( MyFunction );
sub MyFunction {
my $var_0 = shift;
if ($var_0 =~ /WA/) {
return "Olympia", "Population is 53,000";
}
elsif ($var_0 =~ /OR/) {
return "Salem", "Population is 172,000";
}
}
perl -I. -MMyModule -le'print join " ", MyFunction( "WA" )'