Workshop

The workshop provides quiz questions to help you solidify your understanding of the material covered and exercises to give you experience in using what you've learned. Try and understand the quiz and exercise answers before you go on to tomorrow's lesson.

Quiz

1:What is a block? What can you put inside a block?
A1: A block is a group of other Perl statements (which can include other blocks) surrounded by curly braces ({}). Blocks are most commonly used in conjunction with conditionals and loops, but can also be used on their own (bare blocks).
2:What's the difference between an if and an unless?
A2: The difference between and if and an unless is in the test: an if statement executes its block if the test returns true; unless executes is block if the test returns false.
3:What makes a while loop stop looping?
A3: The while loop stops looping when its test returns false. You can also break out of a while loop, or any loop, with last.
4:Why are do loops different from while or until loops?
A4: do loops are different from while or until loops in several ways. First, their blocks are executed before their tests, which allows you to execute statements at least once (for while and until, the block might not execute at all). Secondly, because the do loop is not actually really a loop (it's a function with a modifier), you cannot use loop controls inside it like last or next.
5:What are the three parts of the part of the for loop in parentheses, and what do they do?
A5: The three parts of the for loop in parentheses are
  • A loop counter initialization expression such as $i = 0

  • A test to determine how many times the loop will iterate, for example $i < $max

  • An increment expression to bring the loop counter closer to the test, for example, $i++.

6:Define the differences between next, last, and redo.
A6: next, last, and redo are all loop control expressions. next will stop executing the current block and start the loop at the top, including executing the test in a for or a while loop. redo is the same as next, except it restarts the block from the first statement in that block without executing the loop control test. last exits the loop altogether without retesting or reexecuting anything.
7:Name three situations in which the $_ variable can be used.
A7: Here are a number of situations that default to the $_ if a variable isn't indicated:
  • while (<>) will read each line into $_ separately

  • chomp will remove the newline from $_

  • print will print $_

  • foreach will use $_ as the temporary variable

8:How does <> differ from <STDIN>?
A8: <> is used to input the contents of files specified on the command line (and as stored in @ARGV). <STDIN> is used to input data from standard input (usually the keyboard).

Exercises

1:Write a script that prompts you for two numbers. Test to make sure that both numbers entered are actually numbers, and that the second number is not zero. If both numbers meet these requirements, divide the first by the second and print the result.
A1: Here's one answer:
#!/usr/local/bin/perl -w

$num1 = 0;
$num2 = 0;

while () {
    print 'Enter a number: ';
    chomp($num1 = <STDIN>);
    print 'Enter another number: ';
    chomp($num2 = <STDIN>);

    if ($num1 =~ /D/ or $num2 =~ /D/ ) {
        print "Numbers only, please.
";
        next;
    } elsif ( $num2 == 0) {
        print "Second number cannot be 0!
";
        next;
    } else { last; }
}

print "The result of dividing $num1 by $num2 is ";
printf("%.2f
", $num1 / $num2 );

2:Rewrite #1 to include a test for negative numbers.
A2: Here's one answer:
#!/usr/local/bin/perl -w

$num1 = 0;
$num2 = 0;

while () {
    print 'Enter a number: ';
    chomp($num1 = <STDIN>);
    print 'Enter another number: ';
    chomp($num2 = <STDIN>);

    if ($num1 =~ /D/ or $num2 =~ /D/ ) { # contains non-digit or -
        if ($num1 =~ /-d+/ or $num2 =~ /-d+/) {  # contains -
            print "Positive numbers only.
";
            next;
        } else { # contains non digit, not -
            print "Digits only.
";
            next;
        }
    } elsif ( $num2 == 0) {
        print "Second number cannot be 0!
";
        next;
    } else { last; }
}

print "The result of dividing $num1 by $num2 is ";
printf("%.2f
", $num1 / $num2 );

3:BUG BUSTER: What's wrong with this script (Hint: there might be more than one error)?
if ($val == 4) then { print $val; }
elseif ($val > 4) { print "more than 4"; }

A3: There are two errors: then is not a Perl keyword; leave it out. And elseif is also not a valid Perl keyword; use elsif instead.
4:BUG BUSTER: What's wrong with this script (Hint: there might be more than one error)?
for ($i = 0, $i < $max, $i++) {
   $vals[$i] = "";
}

A4: The expressions inside the for control expression should be separated with semicolons, not commas.
5:BUG BUSTER: How about this one?
while ($i < $max) {
   $vals[$i] = 0;
}

A5: Syntactically, that loop is correct, but there's no way it'll ever exit—there's no increment for $i inside the body of the loop.
6:Rewrite the names.pl script from yesterday to read from a file of names instead of from the standard input.
A6: Here's one answer:
#!/usr/local/bin/perl -w

%names = ();   # hash of names
$fn = '';      # first name
$ln = '';      # last name

while (<>) {
    chomp;
    ($fn, $ln) = split;
    $names{$ln} = $fn;
}

foreach $lastname (sort keys %names) {
    print "$lastname, $names{$lastname} 
";
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset