The Perl unless operator

Perl unless FAQ: Can you share some examples of the Perl unless operator?

Perl has a cool keyword named "unless" that can make your code easier to read and write from time to time. The Perl unless operator is similar to the Perl "if" keyword ... but a little different.

A Perl unless/else example

Here's a quick example (inspired by one of the Star Trek movies) that shows how to use the Perl unless syntax. Hopefully it's fairly easy to read, in part due to the unless operator:

$TRUE  = 1;
$FALSE = 0;

# my "destroy" function
sub destroy_planet_earth 
{
  print "Sorry, I had to destroy the earth.\n";
}

# the "main" program
$whales_are_singing = $TRUE;

# the perl unless operator
unless ($whales_are_singing)
{
  destroy_planet_earth();
}
else
{
  print "Earth is safe ... for now.\n";
}

Perl unless example - Discussion

Okay, maybe that wasn't the greatest example, but the Perl unless operator can make your code easier to read at times. Note from that example that you can easily use the unless operator with an else clause (i.e., a Perl unless/else statement).

While I'm in the neighborhood, here's how I would write the "main" portion of that code just using a Perl if statement:

# the "main" program
$whales_are_singing = $TRUE;
if ($whales_are_singing)
{
  print "Earth is safe ... for now.\n";
}
else
{
  destroy_planet_earth();
}

As you can see from this example, the Perl unless operator has a way of reversing a normal Perl if/then statement (and in better examples, the unless operator makes your code easier to read than the if operator.)

Perl unless as an expression modifier

There's another way you'll commonly see the Perl unless operator used, and that's as an "expression modifier". (An expression modifier is where you follow a normal expression with a modifier that controls the execution of that expression.)

Here's a quick example of the Perl unless operator used as an expression modifier:

destroy_planet_earth() unless $whales_are_singing;

In my opinion, that's a very readable Perl statement, and it's made possible by the Perl unless operator, and the expression modifier syntax.

More Perl unless examples?

There may be other uses of the "Perl unless" syntax that I'm not currently thinking of (but I think this shows a very common use). If you have a Perl unless example you'd like to share, just leave a comment below.