O'Reilly logo

Learning Perl, Second Edition by Randal L. Schwartz, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

A.8. Chapter 9

  1. Here's one way to do it:

    sub card {} # from previous exercise
    
    while () { ## NEW ##
        print "Enter first number: ";
        chomp($first = <STDIN>);
        last if $first eq "end"; ## NEW ##
    
        print "Enter second number: ";
        chomp($second = <STDIN>);
        last if $second eq "end"; ## NEW ##
    
        $message = &card($first) . " plus " .
            card($second) . " equals " .
            card($first+$second) . ".\n";
        print "\u$message";
    } ## NEW ##

    Note the addition of the while loop and the two last operators. That's it!

  2. Here's one way to do it:

    {
      print "Enter a number (999 to quit): ";
      chomp($n = <STDIN>);
      last if $n == 999;
      $sum += $n;
      redo;
    }
    
    print "the sum is $sum\n";
    We're using a naked block with a redo and a last to get things done this time. Start by printing the prompt and grabbing the number. If it's 999, exit the block with last and print out the sum on exit. Otherwise, we add to our running total and use redo to execute the block again.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required