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 twolast
operators. That’s it!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 alast
to get things done this time. We start by printing the prompt and grabbing the number. If it’s 999, we exit the block withlast
and print out the sum on exit. Otherwise, we add to our running total and useredo
to execute the block again.
Get Learning Perl on Win32 Systems 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.