start page | rating of books | rating of authors | reviews | copyrights

Book Home Programming PerlSearch this book

4.3. 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/elseBLOCKs, only the first one whose condition evaluates to true is executed. If none of them is true, then the elseBLOCK, 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.



Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.