next up previous contents
Next: The for statement Up: Perl Statements Previous: Statement Blocks and Local

If/Unless statement

The if statement has a variety of forms. The simplest is:

if (expression)
  {  true_statement_1;
     .....
     true_statement_n;
  }

which means that if expression is evaluated as being true then execute the block of statements.

In Perl, false is regarded as any expression which evaluates to 0. true any expression which is not false (non-zero).

An else may be added to provide a block of statements to be executed upon a false evaluation of the expression:

if (expression)
  {  true_statement_1;
     .....
     true_statement_n;
  }
else
  {  false_statement_1;
     .....
     false_statement_n;
  }

Curly braces are required for each block even if only one statement is present.

For example:

$age = ; # whatever ??
if ($age < 18)
  { print "You cannot Vote or have a beer, yet.\n";
  }
else
  { print "Go and Vote and then have a beer.\n";
  }

There is an unless statement in Perl which can be regarded as the negative of if: If the control expression is not true, do ....

$age = ; # whatever ??
unless ($age < 18)
 
  { print "Go and Vote and then have a beer.\n";
  }

unless can have an else, too.

If you have more than one branch then the elsif can be added to the if. You cannot have an else if in Perl -- you must use elsif.

$age = ; # whatever ??
if ($age < 16)
  {
    print "Hi, Junior\n";
  }
elsif ($age < 17)
 {
    print You can ????\n";
  }
elsif ($age < 18)
 {
    print You can learn to drive\n";
  }
else
  { print "Go and Vote and then have a beer.\n";
  }

Note: The last else.



 

dave@cs.cf.ac.uk