Learn Perl's unless control structure _perl

Source: Internet
Author: User
Tags learn perl

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

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.