For example:
Copy 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. This is like using the if control structure to determine the opposite conditions. It is also similar to an independent else clause. That is to say, when you cannot understand an unless statement, you can replace it with the following if statement:Copy 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 running efficiency. The two statements should be translated into the same internal bytecode. Another method to rewrite is to take the Inverse Operator! To deny the condition:Copy 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 ";
}
Generally, you should select the easiest way to write code, because this is usually the easiest way to maintain programmers. If you use if to express the most appropriate information, you can write it as well. But in more cases, the use of unless can make your expression more natural.
Unless else clause
In fact, even the unless structure can also use else statements. Although such syntax is supported, it may cause confusion:
Copy 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 the if statement is used, we can write it as follows:
If ($ mon = ~ /^ Feb /){
Print "Do you see what's going on here? \ N ";
} Else {
Print "This month has at least thirty days. \ n ";
}