A.3. Chapter 4

  1. Here's one way to do it:

    print "What temperature is it? ";
    chomp($temperature = <STDIN>);
    if ($temperature > 72) {
        print "Too hot!\n";
    } else {
        print "Too cold!\n";
    }

    The first line prompts you for the temperature. The second line accepts the temperature for input. The if statement on the final 5 lines selects one of two messages to print, depending on the value of $temperature.

  2. Here's one way to do it:

    print "What temperature is it? ";
    chomp($temperature = <STDIN>);
    if ($temperature > 75) {
        print "Too hot!\n";
    } elsif ($temperature < 68) {
        print "Too cold!\n";
    } else {
        print "Just right!\n";
    }

    Here, we've modified the program to include a three-way choice. First, the temperature is compared to 75, then to 68. Note that only one of the three choices will be executed each time through the program.

  3. Here's one way to do it:

    print "Enter a number (999 to quit): ";
    chomp($n = <STDIN>);
    while ($n != 999) {
        $sum += $n;
        print "Enter another number (999 to quit): ";
        chomp($n = <STDIN>);
    }
    print "the sum is $sum\n";

    The first line prompts for the first number. The second line reads the number from the terminal. The while loop continues to execute as long as the number is not 999.

    The += operator accumulates the numbers into the $sum variable. Note that the initial value of $sum is undef, which makes a nice value for an accumulator, because the first value added in will be effectively added to 0 (remember that undef used as a number is zero).

    Within the loop, we must prompt for and ...

Get Learning Perl, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.