Reputation: 21
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.
Upvotes: 1
Views: 219
Reputation: 385734
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 v5.14;
use warnings;
use Exporter qw( import );
our @EXPORT = qw( MyFunction );
sub MyFunction {
my $var_0 = shift;
if ( $var_0 eq "WA" ) {
return "Olympia", "Population is 53,000";
}
elsif ( $var_0 eq "OR" ) {
return "Salem", "Population is 172,000";
}
}
perl -I. -MMyModule -le'print for MyFunction( @ARGV )' WA
You probably want the two values in different shell vars. You could use the shell's read
with the above, or you could use the following:
package MyModule;
use v5.14;
use warnings;
use Exporter qw( import );
use String::ShellQuote qw( shell_quote );
our @EXPORT = qw( MyWrappedFunction );
sub MyFunction {
my $var_0 = shift;
my ( $var_1, $var_2 );
if ( $var_0 eq "WA" ) {
( $var_1, $var_2 ) = ( "Olympia", "Population is 53,000" );
}
elsif ( $var_0 eq "OR" ) {
( $var_1, $var_2 ) = ( "Salem", "Population is 172,000" );
}
return VAL1 => $var_1, VAL2 => $var_ 2;
}
sub MyWrappedFunction {
my %d = MyFunction( @_ );
say "$_=" . shell_quote( $d{$_} ) for keys( %d );
}
eval "$( perl -I. -MMyModule -e'MyWrappedFunction( @ARGV )' WA )"
(I'm assuming a sh
-like shell is used.)
Upvotes: 4
Reputation: 16970
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;'
Upvotes: 5