Section 10.1. The unless Control Structure


10.1. The unless Control Structure

In an if control structure, the block of code is executed only when the conditional expression is true. If you want to execute a block of code only when the conditional is false, change if to unless:

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

Using unless says to run the block of code unless this condition is true. It's like using an if test with the opposite condition. Another way to say it is that it's like having the else clause on its own. Whenever you see an unless you don't understand, you can rewrite it (in your head or in reality) as an if test:

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

It's no more or less efficient, and it should compile to the same internal byte codes. Another way to rewrite it would be to negate the conditional expression by using the negation operator (!):

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

You should pick the way of writing code that makes the most sense to you since that will probably make the most sense to your maintenance programmer. If it makes the most sense to write if with a negation, do that. More often, you'll likely find it natural to use unless.

10.1.1. The else Clause with unless

You can have an else clause with an unless. Though this syntax is supported, it can be confusing:

     unless ($mon =~ /^Feb/) {       print "This month has at least thirty days.\n";     } else {       print "Do you see what's going on here?\n";     } 

Some people may wish to use this, especially when the first clause is short (perhaps only one line) and the second is several lines of code. But we'd make this one a negated if or maybe swap the clauses to make a normal if:

     if ($mon =~ /^Feb/) {       print "Do you see what's going on here?\n";     } else {       print "This month has at least thirty days.\n";     } 

Remember you're always writing code for two readers: the computer that will run the code and the human being who has to keep the code working. If the human can't understand what you've written, pretty soon the computer won't be doing the right thing either.



Learning Perl
Learning Perl, 5th Edition
ISBN: 0596520107
EAN: 2147483647
Year: 2003
Pages: 232

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net