main
December 19th, 2024    

CIS 2.55
Main
Files
Syllabus
Overview
Links
Homeworks

UPLOAD HOMEWORKS

Notes
0001
0002
0003
0004
0005
0006
0007
0008
0009
0010
0011
0012
0013
0014
0015
Bayes (src)

Tests
Sample Midterm
Sample Final

Misc
Arithmetics
Fourier Mult

Notes 0003

Control Structures Intro

(if, while, for and other control flow statements)

Just as almost every other programming language, Perl has many control structures, like if statements, and various kinds of loops.

if Statements

If statements behave just as you'd expect them to behave from languages like C/C++, Java, etc. An example of an if statement would be something like:

if($a == 0){
   print "a is 0\n";
}

You can also do the usual else if except now, you just use elsif:

if($a == 0){
   print "a is zero\n";
}elsif($a == 1){
   print "a is one\n";
}

And as usual, there is also the else:

if($a == 0){
   print "a is zero\n";
}elsif($a == 1){
   print "a is one\n";
}else{
   print "a is something!\n";
}

Notice that we used { and } braces even though we only have one statement inside these if constructs. We must use them in Perl. This applies to all flow control structures.

unless Statement

There is also the cousin of the if statement called: unless. While the if statement will execute if the condition is true, the unless will execute "unless" the condition is true. For example:

unless($a == 0){
   print "a is NOT zero";
}

It says "unless $a is zero, do this..."

Unexpected uses of if and unless

Well, what unexpected thing can we get from an if statement? Well, how about this code:

print "a is less than ten" if $a < 10;

Notice that the if statement is used after the statement that it effects. We can also do the same thing with unless.

Switch Construct (kind of)

You'll be happy to know that there is no elaborate switch statement to memorize. Perl simply doesn't have it.

For those of you who are unhappy to learn of such an important absence in the language, you'll be happy to learn that Perl is so flexible, as to enable you to simulate a switch statement with its current constructs:

SWITCH: 
{
   if(somecondition){
      statements...
      last SWITCH;
   }
   if(somecondition){
      statements...
      last SWITCH;
   }
   DEFAULT: 
   {
       statements...
       last SWITCH;
   }
}

Notice that it has all the key points of a switch statement; the only issue is that it is still just a bunch of if statements; which is what a switch statement is anyway.

Looping

There are several looping structures in Perl, and as you'll see later, they're mostly different variations of the same thing.

Let's deal with the while loop (and until):

while Loop

The while loop is the usual while loops that all programmers are familiar with. It continues looping while some condition is satisfied. For example:

$i = 0;
while($i < 10){
   print "i is $i\n";
   $i++;
}

Would loop until $i hits 10, that's when it terminates the loop. Very often, this type of loop is used to read input (either from console, or from an input file). For example, to read lines from standard input, and print them out one by one, you'd write something like this:

while($line = <>){
   print $line;
}

Note that the <> reads one line from standard input (including the newline character). In true Perl spirit, we can rewrite the above code as simply:

while(<>){
   print;
}

Or, better yet (similar to our if statement format):

print while <>;

As you can see, you can minimize the code beyond recognition. As a Perl developer, you must always balance functionality with readability (this is probably why most people who don't know Perl think it is an ugly language).

until Loop

Just like the if statement has unless, the while loop has until counterpart. It is essentially a negative loop, that will execute until some condition is satisfied. For example:

$i = 0;
until($i == 10){
   print "i is $i\n";
   $i++;
}

In this loop, once $i hits 10, the loop terminates.

for Loop

The for loop can behave as the usual traditional for loop you're familiar with from languages like C/C++.

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

This loop above just counts 0 to 9, and displays the numbers. Nothing particularly interesting.

foreach Loop

There is also a list processing loop, that traverses elements in a list. We can easily define it as such:

foreach $name (john,bill,jane,bob,tom) {
   print "loop: $name\n";
}

Usually, this is a lot more useful for non-hard coded lists, for example:

@names = (john,bill,jane,bob,tom);

foreach $name (@names){
   print "hi $name!\n";
}

Another freaky thing you should notice about the previous two examples is that when defining strings, we don't specify any quote character. Namely:

@names = (john,bill,jane,bob,tom);

Defines a list (array) named @names, that contains a list of names. The individual constants john, etc., are converted to strings automatically.

Modified foreach Loop

In our foreach loop, we are not required to specify where each instance of the list goes. For example, converting our previous example to the following still works:

@names = (john,bill,jane,bob,tom);

foreach (@names){
   print "hi $_!\n";
}

Notice that instead of $name inside the print statement, we use $_. This is the scalar to which everything happens if no specific scalar is specified. Very often, you can write huge chunks of code without ever referring to any scalars, and simply implicitly use this $_.

This is how our weird while loop worked:

print while <>;

The <> reads a string, since we don't specify where to store anything, it is stored in $_. We then call print, and since again, we don't specify what exactly we are printing, it simply prints $_.

Now, get ready for a little shock. The for and foreach loops are EXACTLY the same thing! You can even say:

@names = (john,bill,jane,bob,tom);

for (@names){
   print "bye $_!\n";
}

Which means, you can do weird things like rewriting the above as:

print "bye $_!\n" for (john,bill,jane,bob,tom);

Which will display "bye john!... " followed by a similar thing for all the other names in the for condition.

We can even do unintuitive things like:

foreach($i=0;$i<10;$i++){
   print "counting $i\n";
}

As you can see, Perl can be bent and twisted into any style of programming you enjoy.

next and last inside Loops

In C/C++ (and in Java, and in C#, etc.) we have loop break and continue statements. In Perl, these are known as last and next respectively.

We can even use labels to name loops, and refer to specific loops with these next and last keywords. Let us first come up with a loop inside a loop:

@fnames = (john,bill,jane,larry,tom);
@lnames = (doe,jones,gates);

foreach $first (@fnames){
   foreach $last (@lnames){
      print "$first $last\n";
   }
}

The above code generates a list of full names. Let's say we want to stop as soon as we hit "bill gates". Now, because we only have both first and last names available to us in the inner most loop, how to we break out of the outer loop? We name the outer loop!

@fnames = (john,bill,jane,larry,tom);
@lnames = (doe,jones,gates);

FNAMES: foreach $first (@fnames){
   foreach $last (@lnames){
      print "$first $last\n";
      last FNAMES if $first eq "bill" and $last eq "gates";   
   }
}

We can do a similar thing for next (and I'll let you experiment with that yourself). Note that the above is just a shorthand for:

@fnames = (john,bill,jane,larry,tom);
@lnames = (doe,jones,gates);

FNAMES: foreach $first (@fnames){
   foreach $last (@lnames){
      print "$first $last\n";
      if($first eq "bill" and $last eq "gates"){
         last FNAMES;   
      }
   }
}

Anyway, that about covers all there is to Perl control structures. Try using various kinds in your programs, and experiment with mixing them with each other (having if statements inside while loops inside for loops, etc.) The only way to learn these things is to practice, a lot.



































© 2006, Particle