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 a block of code to be executed 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 just 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. That is, whenever you see an unless that you don't understand, you can rewrite it (either in your head or in reality) to be 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. Or, 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";
}

Generally, 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, however, you'll probably find it natural to use unless.

10.1.1 The else Clause with unless

You could even have an else clause with an unless. While this syntax is supported, it's potentially 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 very short (perhaps only one line) and the second is several lines of code. But we'd make this one a negated if, or maybe simply 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";
}

It's important to remember that 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: 2001
Pages: 205

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