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

I am issuing a command to system and trying to code to catch a failure (believing this to be good practise).
Unfortunately the result is that my script thinks the command has failed yet when I check it actually executed fine.
Suggestions as to where I am going wrong and or how I should be doing this please?

#!c:/perl/bin/perl -w if ($result=`.\path\command`) { print "Successful\n" ; &doSomethingIfNecessary(); } else { print "Unsuccessful\n" ; &ohDearTimeToDie(); } exit 0;
Wibble: The command I am running is “\nsr\bin>sjimm scsidev@6.6.0 slot X slot Y”
This moves a tape in an autochanger from source slot X to destination slot Y. Run at the command line the command does not return anything when successful. Run from the script the result is "Unsuccessful" is printed but the tape has been moved. OS is Win2k

Replies are listed 'Best First'.
Re: Successful returns Unsuccessful
by jasonk (Parson) on Mar 10, 2003 at 15:12 UTC

    You need to read the documentation for system. Shell commands have a 0 exit code to indicate success, which perl interprets as false. Non-0 exit codes indicate various failures.

Re: Successful returns Unsuccessful
by Tomte (Priest) on Mar 10, 2003 at 15:14 UTC

    1. A shell-command returns '0' on success, and $? > 0 on failure.
    This one-liner illustrates this (on unix):

    perl -e 'print "true" if `/bin/true`, $?; print "false" if `/bin/false +`, $?' false

    2. Your code will state a succesful call if the command produced any output on STDOUT, check $? for the return-code instead of the output!

    regards,
    tomte


Re: Successful returns Unsuccessful
by zby (Vicar) on Mar 10, 2003 at 15:17 UTC
    $result=`.\path\command` this code makes $result contain the output of the command. That output is then checked by your if. So if it is empty or if it evaluates to 0 as a number then your program prints "Unsuccessful\n".

    As the others have allready stated you probably should check the $? variable - not the program output.

Re: Successful returns Unsuccessful
by 2mths (Beadle) on Mar 10, 2003 at 15:40 UTC
    Thankyou all. I feel like a dunce, but a more educated dunce!

    I can't believe I've not hit this before. Looking over my scripts though I can see why. I always used to issue
    $result = `command`; then evaluate $result to see if it had worked. Also I've never issued a command before that returns nothing when successful (NT is normally fairly verbose). Here I've changed my coding style together and have tripped over my own shoelaces.

    I will try to look system documentation again. I'm not too hot on Perls in built variables. I've got the hang of $_ but not a lot else, what should I feed into perldoc to gain enlightenment?
      >> what should I feed into perldoc to gain enlightenment?

      "perldoc perlvar" will help.