Previous Table of Contents Next


Quiz 3

1.  Which of the following statements is false?
a.  An elsif clause must always contain parentheses.
b.  $a = $a + 3; and $a++; $a++; $a++; both increment $a by three.
c.  The action following an else must be in curly braces.
d.  An elsif statement must follow every else.
2.  What’s printed by the following code?
$x = “lollipop”;
$y = $x . $x;
$y .= “s\n”;
print $y;
a.  lollipoplollipops (followed by a newline)
b.  lollipop lollipops (followed by a newline)
c.  $x . $xs (followed by a new line)
d.  Nothing—Perl will barf on the code.
3.  What is the value of $name at the end of the following program?
#!/usr/bin/perl
$name = ‘Will’;
if ($name eq “Will”) { $name .= ‘i’; }
else { chop $name; }
if ($name ne ‘Willi’) { $name .= ‘ly’; }
elsif ($name eq ‘Bill’) { $name .= ‘iard’; }
else {$name .= ‘am’; }
a.  Willy
b.  William
c.  Billiard
d.  Willily
4.  Which statement looks like it does what the programmer wants?
a.  print ‘$29.95 won’t buy much these days.’;
b.  print “$29.95 is a drop in the bucket.\n”;
c.  print “\$29\.95 won\’t even get you a movie ticket and popcorn.\n”;
d.  print $29.95 won’t buy much these days.

Exercise 3

Difficulty: Medium

Modify tickets3 to give the user a choice of two movies. It should ask which movie the user wants to see and then confirm that choice.

Session 4
Introduction to Loops

Loops execute the same statements over and over until some stop condition is satisfied (Figure 1-6). There are three commonly used looping constructs in Perl: while, foreach, and for. We’ll explore them (in that order) in Sessions 4, 5, and 6.


Figure 1-6  A while loop


The while Loop
while ( CONDITION ) { BODY } repeatedly executes the statements in BODY as long as CONDITION is True.

To understand loops better, let’s play with a little algorithm that demonstrates loopish behavior:

Step 1: Start with some integer n.
Step 2: If n is even, divide it by 2. Otherwise, multiply it by 3 and add 1.
Step 3: If n is 1, stop; otherwise go to Step 2.

Eventually, n will become 1 (we think; no one really knows for sure), but the number of steps will vary depending on the choice of n. 16 plummets to 1 quickly. 27 takes much longer. Experiment!

Let’s rewrite these steps in a slightly different way:

Step 1: While (n isn’t 1), do the following
Step 2: If (n is even) {divide it by 2} else {multiply it by 3 and add 1}.

The meander program (Listing 1-11) implements this algorithm using a while loop and an if...else statement.

Listing 1-11 meander: Using a while loop

#!/usr/bin/perl -w
print ‘Please type an integer: ’;
$num = <>;
chomp $num;
while ($num != 1) {               # as long as $num isn’t 1, do:
    print “$num ”;
                                   #  If $num is even, halve it.
                                   # Otherwise, multiply by 3 and add 1.
    if (($num % 2) == 0) { $num /= 2; }
    else                { $num *= 3;  $num++; }
}
print $num, “\n”;                   # print the last number (which must
                                    # be 1, since the loop finished).

The while loop first tests to see whether $num is equal to 1. If it isn’t, the statements inside the outer curly braces are executed. Then Perl returns to the top of the loop and checks $num again. This continues until $num finally does become 1, at which time the loop exits and Perl moves to the next statement in the program.

Here’s meander in action:

        % meander
RESULT: Please type an integer: 15
        15 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1

        % meander
RESULT: Please type an integer: 20
        20 10 5 16 8 4 2 1

        % meander
RESULT: Please type an integer: 256
        256 128 64 32 16 8 4 2 1

Beware Infinite Loops!

Suppose a loop has the condition ($num != 1. Then there should be some statement inside the loop that modifies $num. In fact, it’s downright critical! Otherwise, $num stays at whatever it was before entering the loop, the condition never becomes FALSE, and the loop never exits. See if you can figure out why these snippets of code loop forever.

#!/usr/bin/perl
$num = 0;
while ($num == 0) {
         print “num is $num.\n”;
}

Bug! The loop variable $num never changes

#!/usr/bin/perl
$num = 1;
while ($num != 10) {
         print “$num is an odd number.\n”;
         $num += 2;
}

Bug! The stop condition is stepped over

The first loop never modifies $num at all. The second loop modifies $num, but not in a way that ever satisfies the stop condition because $num skips right from 9 to 11.

The % Operator

The % operator (pronounced “mod,” short for “modulus”) yields the remainder when the right side is divided by the left. Some examples:

        % perl -e ‘ print 17 % 5’
RESULT: 2

        % perl -e ‘ print 6 % 3’
RESULT: 0

        % perl -e ‘ print 25 % 20’
RESULT: 5

Because all even numbers are divisible by 2, the remainder will be 0, so ($num % 2) is 0 only if $num is even. (And should you ever find yourself needing a statement like $big = $big % 2, you can abbreviate it just like the assignment operators you saw earlier: $big %= 2.)


Previous Table of Contents Next