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/local/bin/perl
use strict 'vars';
use warnings;

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 <= 40) {
   $evaluation = "failed";
} elsif ($grade > 40 and $grade <= 60) {
   $evaluation = "bad";
} elsif ($grade > 60 and $grade <= 80) {
   $evaluation = "good";
} elsif ($grade > 80 and $grade <= 100) {
   $evaluation = "very good";
} else {
   $evaluation = "invalid input - grade should be between 0 and 100";
}

# print out the evaluation

print "Evaluation: $evaluation\n";


Table of Contents.
Next.