Control Structures

Variations on the if statement

Without else:

if (expression) {         # condition
  __________________;
  __________________;    # do if true
  __________________;  
}
 

Multiple choices, using elsif:

if (expression1) {         # condition
  __________________;
  __________________;
  __________________;
   
} elsif (expression2) {
  __________________;
  __________________;
  __________________;
 
}elsif (expression3){
  __________________;
  __________________;
  __________________;
 
}else {
  __________________;
  __________________;
  __________________;
} 

Example:

#!/usr/bin/perl

my ($grade, $evaluation);

# receive a grade from user

print "Enter student grade (between 0 - 100): ";
$grade = <STDIN>;
chomp ($grade);

# decide what will the evaluation be

if ($grade >=0 and $grade <= 60) {
   $evaluation = "failed";
} elsif ($grade > 60 and $grade <= 70) {
   $evaluation = "enough";
} elsif ($grade > 70 and $grade <= 80) {
   $evaluation = "good";
} elsif ($grade > 80 and $grade <= 90) {
   $evaluation = "very good";
} elsif ($grade > 90 and $grade <= 100) {
   $evaluation = "excellent";
} else {
   $evaluation = "invalid input - grade should be between 0 and 100";
}

# print out the evaluation

print "Evaluation: $evaluation\n";


Table of Contents.
Previous | Next.