Control Structures

The while loop

while (expression) {    # condition
  __________________;
  __________________;  # do if expression is true
  __________________;  # then go back and recheck expression
}

The until loop

until (expression) {    # condition
  __________________;
  __________________;  # do if expression is false
  __________________;  # then go back and recheck expression
}

Example 1: count from a given number up to 10

#!/usr/bin/perl

# receive a number from user

print "Please, enter a number: ";
my $n = <STDIN>;
chomp ($n);

#count up to 10

while ($n <= 10) {
  print "$n\n";
  $n++;                #same as $n +=1;
};

#print DONE

print "DONE\n";

Note that if the entered number is greater than 10, the while loop will never be executed.

Example 2: same program, but using until loop

#!/usr/bin/perl

# receive a number from user

print "Please enter a number: ";
my $n = <STDIN>;
chomp ($n);

#count up to 10

until ($n > 10) {
  print "$n\n";
  $n++;                    #same as $n +=1;
};

#print DONE

print "DONE\n";


Table of Contents.
Previous | Next.