Previous: Comments Index Next: Control flow

Conditionals

edit

The if statement

edit

The if statement is the primary conditional structure in Perl. The syntax is as follows:

if (''boolean expression'') {
    ''statement'';
}

If the boolean expression evaluates to true, the statements between the two braces will be executed. The braces around statements are mandatory, even if there is only one statement (unlike C or Java).

An alternative syntax to the if statement may be used on a single statement. This involves putting the conditional at the end of the statement rather than before, and does not include braces:

''statement'' if (''boolean expression'') ;

The following statements are synonymous:

if ($x == 20) { print "hello"; }

print "hello" if ($x == 20);

You should choose whichever one is clearer in a given situation. For example, the following is legal, but unclear:

foreach my $word (@words) {
    if ($word eq 'end') { last; }
    print "$word\n";
}

This hides the last (which is like break, and ends the loop) over at the right. Instead, use a postfix if:

foreach my $word (@words) {
    last if $word eq 'end';
    print "$word\n";
}

The boolean expression conditional can contain any one of the comparison operators covered in the next section.

Multiple conditions can be checked together using the boolean expression operators:

  • && - logical and, C style; used for most conditionals
  • and - logical and, but with a lower precedence; used for flow control
  • || - logical or, C style; used for most conditionals
  • or - logical or, but with a lower precedence; used for flow control
  • ! - logical not, C style
  • not - logical not, but with a lower precedence
if (($x == 20) || (($x > 0) && ($x < 10) && !($x == 5))) {
    print "x is equal to 20 or either between 0 and 10, but not 5.\n";
}

Conditional statements can also be extended with the elsif and else structures:

 if (''boolean expression 1'') {
     ''statement 1;''
 } elsif (''boolean expression 2'') {
     ''statement 2;''
 } else {
     ''statement 3;''
 }

Note that an if statement is followed by any number (including zero) of elsif statements, and finally an optional else statement. The statements of an elsif will be executed, if its boolean expression is true, and no preceding (els)if statement's boolean expression is true. The trailing else (if present) is executed, if none of the preceding statements' boolean expressions are true.

Shorthand if ... else notation

edit

If you want to shorten the conditional into one line, you may use the shortcut syntax:

  This code uses the shorthand syntax within a line.
my $bar = 'exists';

my $whatExists = (exists $foo) ? $bar : 'does not exist';
$whatExists will be equal to 'exists', if $foo is defined before, and 'does not exist' otherwise


Previous: Comments Index Next: Control flow