Skip to Content
Learning Perl, 6th Edition
book

Learning Perl, 6th Edition

by Randal L. Schwartz, brian d foy, Tom Phoenix
June 2011
Beginner content levelBeginner
386 pages
11h 33m
English
O'Reilly Media, Inc.
Content preview from Learning Perl, 6th 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[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 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

Mastering Perl, 2nd Edition

Mastering Perl, 2nd Edition

brian d foy
Learning Perl, 7th Edition

Learning Perl, 7th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix
Perl in a Nutshell, 2nd Edition

Perl in a Nutshell, 2nd Edition

Nathan Patwardhan, Ellen Siever, Stephen Spainhour

Publisher Resources

ISBN: 9781449311063Errata PageSupplemental Content