Skip to Main Content
Programming Perl, 3rd Edition
book

Programming Perl, 3rd Edition

by Larry Wall, Tom Christiansen, Jon Orwant
July 2000
Intermediate to advanced content levelIntermediate to advanced
1104 pages
35h 1m
English
O'Reilly Media, Inc.
Content preview from Programming Perl, 3rd Edition

if and unless Statements

The if statement is straightforward. Because BLOCKs are always bounded by braces, there is never any ambiguity regarding which particular if an else or elsif goes with. In any given sequence of if/elsif/else BLOCKs, only the first one whose condition evaluates to true is executed. If none of them is true, then the else BLOCK, if there is one, is executed. It's usually a good idea to put an else at the end of a chain of elsifs to guard against a missed case.

If you use unless in place of if, the sense of its test is reversed. That is:

unless ($x == 1) …

is equivalent to:

if ($x != 1) …

or even to the unsightly:

if (!($x == 1)) …

The scope of a variable declared in the controlling condition extends from its declaration through the rest of that conditional only, including any elsifs and the final else clause if present, but not beyond:

if ((my $color = <STDIN>) =~ /red/i) {
    $value = 0xff0000;
}
elsif ($color =~ /green/i) {
    $value = 0x00ff00;
}
elsif ($color =~ /blue/i) {
    $value = 0x0000ff;
}
else {
    warn "unknown RGB component `$color', using black instead\n";
    $value = 0x000000;
}

After the else, the $color variable is no longer in scope. If you want the scope to extend further, declare the variable beforehand.

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
Programming the Perl DBI

Programming the Perl DBI

Tim Bunce, Alligator Descartes
Perl in a Nutshell, 2nd Edition

Perl in a Nutshell, 2nd Edition

Nathan Patwardhan, Ellen Siever, Stephen Spainhour

Publisher Resources

ISBN: 0596000278Supplemental ContentErrata