How Do I Get Both The Return Value And Text In Perl? Backticks vs. System() (Perl 5.10)
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?
In the meantime, if you found this article useful, feel free to buy me a cup of coffee below.