http://www.perlmonks.org?node_id=94070


in reply to Re (tilly) 3: Seeking Feed back
in thread Seeking Feedback on Chat Program (was Seeking Feed back)

And as a side-note, something I learned the other day for error handling in system calls :

system("/usr/bin/scp $file $username\@$host:$remoteFile"); die "System call to scp command failed! : $!\n" if ($? != 0);

The special variable $? returns a boolean value for success or fail on system calls. So the above snippet performs a reliable "or die" check on your command. A handy one to know, especially as system tends to be a little unreliable in terms of error checking / return values when using a straight die, IMHO.

Update: as per comments below, not a "boolean" in the strict sense of the word. Call it an "azatoth boolean" :)

Azatoth a.k.a Captain Whiplash

Make Your Die Messages Full of Wisdom!
Get YOUR PerlMonks Stagename here!
Want to speak like a Londoner?

Replies are listed 'Best First'.
Re (tilly) 5: Seeking Feed back
by tilly (Archbishop) on Jul 05, 2001 at 18:01 UTC
    Actually $? is not a boolean. As documented in perlvar, it is the return code of the last system call. That is 0 for success, and all else is an error. If the error is under 256, then it is a system error. If the error is over, then divide by 256 and you have the program's return code. The return code of your programs are set by exit, are 0 by default, and are set from $? on a die.

    Unfortunately that means that every program has its own possible meanings for exit codes. Traditionally, however, 1 means "Error, but not an important one" and 2 means "Bad error". For instance rm on my system will return 1 if you don't give it any files to delete, but a 2 if you try to delete something and it can't.

Re3: (Azatoth): Seeking Feed back
by pmas (Hermit) on Jul 05, 2001 at 18:03 UTC
    Nice. I think this could be done even simpler and more readable using unless instead of if !=:
    system("/usr/bin/scp $file $username\@$host:$remoteFile"); die "System call to scp command failed! : $!\n" unless ($?);

    pmas

    To make errors is human. But to make million errors per second, you need a computer.