Search code examples
perlsystemreturn-value

Perl: system return code is 256 instead of 0


I have an oneliner (perl 5 on Windows 7/10):

C:\Windows>perl -e "$x=system('echo c:\users');print $x";

which gives me the expected outputs:

c:\users
0

But if I have this:

C:\Windows>perl -e "$x=system('explorer c:\users');print $x";

this gives me:

256

and opens the folder.

I'm curious why the output is not 0 since the command executed correctly.

Similar question is here but it was not answered. This question here is more concrete. Maybe somebody can answer this specific issue.

UPDATE 1:

(1) I corrected the path from c:\user to c:\users. The former path was wrong and file explorer C:\Users\giordano\Documents was opened. With this correction the correct file folder is openend but still returns 256.

(2) Better coding:

C:\Windows>perl -e "system('explorer c:\users');print $?";

Solution

  • From the system function docs:

    The return value is the exit status of the program as returned by the wait call. To get the actual exit value, shift right by eight (see below).

    The same value is set in $? which documents this further:

    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.

    Also note that either can be set to -1 if there was a fork or exec error (in which case the errno is set in $!).

    So this means that when executing your second command, it indicated an exit status of 1 (256 >> 8). I don't know what that means in the context of Windows.