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

hi, I'm running a unix program through perl using the system command. I want to be able to get the return value of the program and use it within my perl code. Is there a way to do this. Right now the return values I get from the system command are always 0 even though my application exits with an ERROR. When I run the application locally it sets the environment variable $status to 4. This is what I'm interested in for my program. i.e. can I do something like this: system($cmd;echo $status); but instead of echoing status get the return value in my program? Thanks!

Replies are listed 'Best First'.
Re: return values with system()
by davorg (Chancellor) on Feb 13, 2007 at 16:56 UTC
Re: return values with system()
by Joost (Canon) on Feb 13, 2007 at 17:06 UTC
    When I run the application locally it sets the environment variable $status to 4. .... system($cmd;echo $status);
    Have you tried that? AFAIK you can't "push" environment variables to the parent process (in this case the shell) on UNIX - i.e. if you set an env variable it will only affect the current process and it's children.

    I would probably just print out the value to STDOUT and retrieve it in the perl process using backquotes. Setting variables and then echo()ing them is useless overhead.

    my $output = `some-program`; print "Output from some-program is '$output'";
    that way you're much more flexible and it's easier to debug since you can immediately see the output if you run the program on its own.

      Thanks. This is what I'll do.
Re: return values with system()
by ikegami (Patriarch) on Feb 13, 2007 at 18:21 UTC

    What exactly are you having problems with? This is quite well documented in system's documentation.

    my $rv = system('perl -e "exit(123)"'); die("Unable to launch command: $!\n") if $rv == -1; die("Child died with signal ", ($rv & 127), "\n") if $rv & 127; die("Child exited with value ", ($rv >> 8), "\n") if $rv >> 8; print("Child exited successfully\n");

    outputs

    Child exited with value 123

    Keep in mind that system("$cmd; echo $status"); will return the error code of the shell used to launch these two commands, which will be the error code of echo if nothing goes wrong.

Re: return values with system()
by sauoq (Abbot) on Feb 13, 2007 at 18:41 UTC
    When I run the application locally it sets the environment variable $status to 4.

    Oh? How do you run it? Do you source it? Eval it? Are you on unix or a unix-like OS? If what you claim is true, you should theoretically be able to system("$cmd; exit \$status") but your command should not be able to affect its parent's shell.

    Oh, wait... do you use csh tcsh or something?... that would explain $status. (I'm bourne-shell-centric, I guess.)

    -sauoq
    "My two cents aren't worth a dime.";