Control Structures

Examples

Problem:

Ask user to enter no. of translated nucleotides in a mRNA sequence, and calculate no. of amino acid in the resulting protein only if the entered number is positive and is divided by 3.

Solutions:

Using the until construct:
#!/usr/bin/perl

my ($nuc, $aa);

print "please enter no. of translated nucleotides: ";
$nuc = <STDIN>;
chomp ($nuc);

until ($nuc > 0 and $nuc % 3 == 0) {
  print "Wrong input! Please reenter number: ";
  $nuc = <STDIN>;
  chomp ($nuc);
}

$aa = $nuc / 3;
print "No. of amino acids: $aa\n";
Using the redo statement:
(See Chapter 9 in the "Learning Perl" book.)
#!/usr/bin/perl

my ($nuc, $aa);

{

  print "please enter no. of translated nucleotides: ";
  $nuc = <STDIN>;
  chomp ($nuc);

  if ($nuc <= 0){
    print "Wrong input - negative or zero number\n";
    redo;
  }

  if ($nuc % 3 != 0){
    print "Wrong input - number not divisible by 3\n";
    redo;
  }

}

$aa = $nuc / 3;
print "No. of amino acids: $aa\n";

Table of Contents.
Back.