Arman Akbarian
UNIVERSITY OF BRITISH COLUMBIA
PHYSICS & ASTRONOMY DEPT.

#!/usr/bin/perl -w

use 5.010;
#########################################
# This document is about various control
# structures in Perl
# AAK: Last Modification
# Tue Sep 11 22:00:53 PDT 2012
# #######################################

# unless is opposite of if:

unless ( 2 < 1 )  {
say "This is unless usage";
}

# until is opposite of while, quits when condition becomes correct

$i = 0;

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

#you can have express way of controlling actions:

$n = 9;
print "$n is bigger than 10" if $n > 10;

$i += 10 until $i > 1000;
say $i;

@fruit = qw( banana apple melon );

sub echoit {
   say "@_";
}

&echoit($_) foreach @fruit;

#naked block is as following:

{
   say "This is naked block";
   my $tmpn = 10.0;
   say $tmpn;
}

#note that variables defined inside the naked block are temporary
#and only belongs to that block so:

say $tmpn;

#will print nothing! (you will see a warning, due to -w option enabled)

#else if structure is as following:

$control = 1;
$control2 = 0;
$control3 = 0;

if ( $control2 ) {say "hi 2!"}
elsif ($control3) {say "hi 3!"}
elsif ($control) {say "this is how elsif works"};

#similar to C ++ and -- will increase or decrease the scalar by 1:

$n = 10;
$n++;
say $n;
$n--;
say $n;

#the for control structure is as following (very similar to C):

for ($i = 1; $i <= 10; $i++) {
   print "i =", $i, "\n";
}

for ($i = 100; $i >=-20; $i -= 10) {
   print "i = ", $i, "\n";
}

#last operator breaks the loop immediately:

for ($i =1; $i <=1000; $i *= 2) {
   print "i = ", $i, "\n";
   if ($i >= 500) {last;}
}
#the next operator will send the operation to the end of
#the loop and start the loop again:

for ($i = 1; $i >= 0.01; $i /= 2) {
   unless ($i == 0.125) {next;}
   say " i = $i"
}

#redo operator says to go back and do the loop again, without
#checking for any condition or changing the loop controller variable:

for ($i = 1; $i <=5; $i++){
   say " i = $i";
   if ($i == 5) {
           $i++;
      redo;
   }
}

#C's Tenary operator ? : is as following:

# expression ? do_this_if_true : do_this_if_false;

$width = 15;

my $size =
   ($width < 10) ? "small" :
   ($width < 20) ? "medium" :
   ($width < 30) ? "large" :
                   "extra-large"; #this it the default

say $size;

#and Perl has AND OR operator by && and ||:

$k = 5;
if ( ($k > 3) && ($k != 4) ) {say "this is AND";}
if ( ($k > 3) || ($k != 5) ) {say "this is OR";}


last update: Wed May 11, 2016