Learning the unless control structure of perl

Source: Internet
Author: User

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 ";
}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.