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

I am using system() command in my program.I need to check its return status i.e. whether it has failed or succeeded. I used $ret = system("my commands"); But $ret prints 0 for both the cases - success as well as failure.
I tried using $? too, but the result is same.

Replies are listed 'Best First'.
Re: return status from system()
by edan (Curate) on May 03, 2004 at 07:19 UTC

    system explains that 'The return value is the exit status of the program as returned by the "wait" call. To get the actual exit value divide by 256.'

    This can be proved using the following commands (assuming you're on a *nix type of OS):

    shell> perl -le 'print(system("true")>>8)'
    0
    shell> perl -le 'print(system("false")>>8)'
    1
    

    If you are only getting 0, that means either:

    • Your commands are returning 0 even in the event of 'failure' - test your commands from the shell by running them and then typing echo $?
    • You are running your commands in the background using &
    • Something else

    I'm sure if you provide more detailed information, we could answer your question better.

    --
    edan

Re: return status from system()
by ambrus (Abbot) on May 03, 2004 at 09:14 UTC

    Checking $? should just work, if the program you called reports the exit status correctly. If what you call is a shell script or other program you wrote, check if it exits with the correct exit status.

    For example this works for me

    $ perl -we 'system "true"; print $?,$/;' 0 $ perl -we 'system "false"; print $?,$/;' 256
Re: return status from system()
by rupesh (Hermit) on May 03, 2004 at 08:01 UTC
    Use  system ("...") and ......
    If 'system' fails to execute, the commands after the 'and' would operate. So you could probably assign an appropriate value to a variable (say $ret="false") after the 'and' clause.