1

I am calling a perl script from a bash script. I want to obtain the return value that the perl script returns in the bash script in order to act on it. When I have the following, the output is a blank line to the console when I expect it to be "good".

bashThing.sh

#!/bin/bash

ARG="valid"
VAL=$(perl -I. -MperlThing -e "perlThing::isValid ${ARG}")
echo $VAL

perlThing.pm

#! /usr/bin/perl -w
use strict;

package perlThing;

sub isValid
{
  my $arg = shift;
  if($arg == "valid")
  {
    return "good";
  }
  else
  {
    return "bad";
  }
}

1;

2 Answers 2

2

You didn't have Perl warnings enabled completely. You would have seen several warnings. I enabled warnings both in bash (using -w on the Perl one-liner), and in Perl with use warnings;. The shebang line is ignored in the .pm file since it is not being executed as a script.

isValid returned a string, but you were ignoring the returned value. To fix that, use print in the one-liner.

You also needed to pass the value to isValid properly.

Lastly, you need to use eq instead of == for string comparison.

bash:

#!/bin/bash

ARG="valid"
VAL=$(perl -w -I. -MperlThing -e "print perlThing::isValid(q(${ARG}))")
echo $VAL

Perl:

use strict;
use warnings;

package perlThing;

sub isValid
{
  my $arg = shift;
  if($arg eq "valid")
  {
    return "good";
  }
  else
  {
    return "bad";
  }
}

1;
Sign up to request clarification or add additional context in comments.

Comments

1

If you expect the value good or bad in $VAR, then you should print them not return them.

Other than printed stuff, the perl process can pass only integer return values to calling program. And you can check that using $? in bash script, this variable stores the return value of last run process.

1 Comment

The Bash variable that stores the return code should be $?, not $@. Can you please check?

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.