Search code examples
perlexit-code

How can I check an exit status of a command?


I have a code snippet:

my @array=("abc","def", "ghi");
print "I am testing exit code\n";
grep /lan/, @array;    
if ($?) {
  print "status is 0\n";
 }
else {
  print "Status is 1\n";
}

I am getting "status is 1" in output, but I want "status is 0". As per my understanding, in @array, "lan" is not found and hence exit status must be non-zero, and thus "status is 0" should be printed.

Why is Perl not giving the right exit code? Please give a correct idea about the exit code theory if I am wrong as per my understanding above?


Solution

  • That is a misuse of the $? special variable. You would only check that variable when you execute an external command via system, backticks, etc. Refer to Error variables for further details.

    In your code, grep is a Perl builtin function; it should not be confused with the grep unix utility of the same name.

    Instead of trying to check for an exit status, you could check the return status:

    use warnings;
    use strict;
    
    my @array=("abc","def", "ghi");
    print "I am testing array\n";
    if (grep /lan/, @array) {
      print "lan is in array\n";
    }
    else {
      print "lan is not in array\n";
    }