O'Reilly logo

Learning Perl, 5th Edition by Tom Phoenix, Randal L. Schwartz, brian d foy

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 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-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) 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. Or, another way to rewrite it would be to negate the conditional expression ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required