Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of the built-in variable $? in Perl [duplicate]

Tags:

perl

system

Possible Duplicate:
perl “dollar sign and question mark” question

I am trying to understand the Perl script written by someone. I don't understand the use of $? in the script. Can anyone explain me the purpose of below line?

 system( "perform_task.sh", "-param1");
    if( ( $? >> 8 ) != 0 ) {
       print( "perform_task.sh failed " );
    } 
like image 233
Ghanta Sairam Avatar asked Sep 06 '25 03:09

Ghanta Sairam


1 Answers

To find the meaning of any variable, you can either type

$ perldoc -v '$?'

on the command line with relatively recent versions of Perl or scan perldoc perlvar installed on your computer. Usually, it is best to read the documentation for the specific version of perl you have, but in a pinch, bearing in mind any possible gotchas due to version differences, the online version will do as well: perldoc -v '$?':

The status returned by the last pipe close, backtick (``) command, successful call to wait() or waitpid(), or from the system() operator. This is just the 16-bit status word returned by the traditional Unix wait() system call (or else is made up to look like it). Thus, the exit value of the subprocess is really ($? >> 8), and $? & 127 gives which signal, if any, the process died from, and $? & 128 reports whether there was a core dump.

Further information can be gleaned from the documentation for perldoc -f system:

If you'd like to manually inspect "system"'s failure, you can check all possible failure modes by inspecting $? like this:

   if ($? == -1) {
       print "failed to execute: $!\n";
   }
   elsif ($? & 127) {
       printf "child died with signal %d, %s coredump\n",
           ($? & 127),  ($? & 128) ? 'with' : 'without';
   }
   else {
       printf "child exited with value %d\n", $? >> 8;
   }

While there is nothing wrong with asking even elementary questions on Stackoverflow, if you actually want to become a capable programmer, you'll need to get into the habit of reading the documentation yourself, and develop the capacity to understand it yourself.

Otherwise, you'll waste valuable time you could be using to solve problems instead on waiting for others to read the documentation for you.

It really doesn't affect the rest of us if you choose never to expend any effort in trying to understand documentation, but it will hurt you in the long run.

like image 153
Sinan Ünür Avatar answered Sep 08 '25 10:09

Sinan Ünür