The unless & die Function in Perl

PERLServer Side ProgrammingProgramming Scripts

The unless function in Perl is the logical opposite to if: statements can completely bypass the success status and only be executed if the expression returns false. For example −

unless(chdir("/etc")) {
   die "Error: Can't change directory - $!";

The unless statement is best used when you want to raise an error or alternative only if the expression fails. The statement also makes sense when used in a single-line statement −

die "Error: Can't change directory!: $!" unless(chdir("/etc"));

Here we die only if the chdir operation fails.

The die Function

The die function works just like warn, except that it also calls exit. Within a normal script, this function has the effect of immediately terminating execution. You should use this function in case it is useless to proceed if there is an error in the program −

chdir('/etc') or die "Can't change directory";
Updated on 29-Nov-2019 11:41:22