For example:
Copy Code code 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 either the condition is true or a block of code is executed. This is like using an if control structure to determine the opposite condition. Another argument is that it is similar to a separate else clause. In other words, when you don't understand a unless statement, you can replace it with the following if statement:
Copy Code code as follows:
if ($fred =~/^ ([a-z_]\w*$/i) {
Don't do anything.
} else {
Print "The value of \ $fred doesn ' t look like a Perl identifier name. \ n ";
}
This operation is not related to the efficiency of operation, both of which should be translated into the same internal byte code. Another way to rewrite it is to take the inverse operator! To negate the condition:
Copy Code code 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 your code, because this is usually the easiest thing to understand for the maintenance programmer. If you use if to express the most appropriate, then it is OK to write. But more often the use of unless can make your expression more natural.
The ELSE clause included with the unless
In fact, you can use the Else statement even in the unless structure, although this syntax is supported, but can cause confusion:
Copy Code code as follows:
#!/usr/bin/perl-w
Unless ($mon =~/^feb/) {
Print "This month has at least thirty days.\n";
} Lese {
Print "Do you have what ' s going on here?\n";
}
#如果用if语句我们可以写成这样:
if ($mon =~/^feb/) {
Print "Do you have what ' s going on here?\n";
} else {
Print "This month has at least thirty days.\n";
}