Chapter 10. More Control Structures

In this chapter, you’ll see some alternative ways to write Perl code. For the most part, these techniques don’t make the language more powerful, but they do make it easier or more convenient to get the job done. You don’t have to use these techniques in your own code, but don’t be tempted to skip this chapter—you’re certain to see these control structures in other people’s code sooner or later (in fact, you’re absolutely certain to see these things in use by the time you finish reading this book).

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[A-Z_]\w*\z/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) as an if test:

if ($fred =~ /\A[A-Z_]\w*\z/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 bytecodes. Or, another way to rewrite it would be to negate the conditional expression ...

Get Learning Perl, 8th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.