Skip to Main Content
Learning Perl, 5th Edition
book

Learning Perl, 5th Edition

by Randal L. Schwartz, Tom Phoenix, brian d foy
June 2008
Beginner content levelBeginner
352 pages
11h 16m
English
O'Reilly Media, Inc.
Content preview from Learning Perl, 5th Edition

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Perl, 6th Edition

Learning Perl, 6th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix
Beginning Perl

Beginning Perl

Curtis Ovid Poe
Learning Perl 6

Learning Perl 6

brian d foy
Mastering Perl

Mastering Perl

brian d foy

Publisher Resources

ISBN: 9780596520106Supplemental ContentErrata Page