zhujian0805 has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks, i run some commands with the function system or get output with backtick ``, If i want to capture the return code of those commands, i have to use $? >> 8. why need to shift right by 8 bits?

Replies are listed 'Best First'.
Re: why divide 256 for the exit code
by almut (Canon) on Sep 07, 2009 at 13:54 UTC

    ...because the lower 8 bits of the exit code might contain information of interest, too (like the signal number that made the process die, and whether it core dumped — see system).  If Perl returned the high 8 bits only (by dividing the exit code by 256 itself prior to returning it), that info would not be available.

      thanks monk, for example, if i write a C program as below: main() { exit(100); } then, i invoke it from perl, and print the exit code, it's 25600. it convert to binary is: 1100100 00000000. so the high 8 bits is: 1100100(100), and the low 8 bits is: 00000000. if this C programm ran abnormally, the low 8 bits may contain info of interest, so use $? & 127 OR $? & 128. am'i right?
        You want 8 bits, not 7. IMHO, if you are doing bit operations, you should use hex (or octal if you are old-school) representations, so that it is clear. In this case, you should & with 0xff
Re: why divide 256 for the exit code
by cdarke (Prior) on Sep 07, 2009 at 19:35 UTC
    This is an example of the baggage Perl carries from its birth on UNIX. It is a reflection the "real" exit code on UNIX, and it even does that on Windows. If you really want to know the rational, then look at the POSIX standard for exit(). In particular "only the least significant 8 bits (that is, status & 0377) shall be available to a waiting parent process."

    Of course when this was designed everyone knew what an exit code looked like, so Perl just did what everyone expected. Nowadays few people know or care how the OS really operates. Sob.