Updated: October 6th, 2009

I'm sure most Perl coders have to face this annoying problem at one point or another: how do you consistently get the return value out of a system call, be at executed via backticks or system()? Backticks return the output of the program with no error code in sight, while system() returns the error code but prints the output instead of putting it into a variable.

The best solution I could find to this problem to date was posted at http://www.perlmonks.org/?node_id=19119 and involved opening a piped filehandle. It worked quite well but always felt like a hack (which it was). Having used the new Perl 5.10 for a few months, I was shocked today to find this new variable that I've been dreaming about for years:

1
${^CHILD_ERROR_NATIVE}

This variable gives the native status returned by the last pipe close, backtick command, successful call to wait() or waitpid(), or from the system() operator. See perlrun for details. (Contributed by Gisle Aas.)

http://search.cpan.org/dist/perl-5.10.0/pod/perl5100delta.pod#New_internal_variables

I've just tested it and it works as described. Finally!.. what else can I say?

● ● ●

Artem Russakovskii is a San Francisco programmer, blogger, and future millionaire (that last part is in the works). Follow Artem on Twitter (@ArtemR) or subscribe to the RSS feed.

In the meantime, if you found this article useful, feel free to buy me a cup of coffee below.



Share
  • nogod

    thats the wrong variable… the exit statius as returned by system has always been available in $?, just like in the shell. that has always been documented… your variable does something else (and is indeed new).

    $? The status returned by the last pipe close, backtick (""") command, successful call to
    wait() or waitpid(), or from the system() operator.

  • http://beerpla.net Artem Russakovskii

    nogod, hrm, you're right, I don't know why I thought it was new. http://search.cpan.org/~rgarcia/perl-5.10.0/pod/perl5100delta.pod#New_internal_variables lists it as new and the only difference I can see between that and $? is the "native" part. What's so native about it, I'm not sure.

    ${^CHILD_ERROR_NATIVE}

    This variable gives the native status returned by the last pipe close, backtick command, successful call to wait() or waitpid(), or from the system() operator. See perlrun for details. (Contributed by Gisle Aas.)