SoFunction
Updated on 2025-04-07

Learn the unless control structure of perl

For example:

Copy the codeThe code is as follows:

unless ($fred =~ /^([A-Z_]\w*$/i) {
  print "The value of \$fred doesn't look like a Perl identifier name. \n";
}

Using unless means that either the condition is true or a block of code is executed. It's like using the if control structure to determine the opposite condition. Another way of saying it is similar to the independent else clause. In other words, when you can't understand a certain unless statement, you can use the following if statement instead:
Copy the codeThe code is as follows:

if ($fred =~ /^([A-Z_]\w*$/i) {
//Do nothing
} else {
   print "The value of \$fred doesn't look like a Perl identifier name. \n";
}

This operation has nothing to do with the operating efficiency, and the two writing methods should be translated into the same internal bytecode. Another method of rewriting is to negate the condition by inverse operator!:
Copy the codeThe code is as follows:

if ( ! ($fred =~ /^([A-Z_]\w*$/i) ) {
  print "The value of \$fred doesn't look like a Perl identifier name. \n";
}

You should usually choose the easiest way to write code, because this is usually the easiest way for maintenance programmers to understand. If it is most appropriate to express it with if, then just write it like this. But in more cases, use unless can make your expression more natural.

Otherwise, else clause

In fact, even in the unless structure, else statements can be used. Although such syntax is supported, it may cause confusion:

Copy the codeThe code is as follows:

#!/usr/bin/perl -w
unless ($mon =~ /^Feb/) {
  print "This month has at least thirty days.\n";
} lese {
  print "Do you see what's going on here?\n";
}
#If we use the if statement we can write it like this:
if ($mon =~ /^Feb/) {
  print "Do you see what's going on here?\n";
} else {
  print "This month has at least thirty days.\n";
}