The digit to word conversion is a trivial hash lookup so that doesn't need a sub, but the input prompt and checking is complicated so that is worth writing a sub for. Consider:
use strict; use warnings; my %toWord = ( "1" => "one", "2" => "two", "3" => "three", "4" => "four", "5" => "five", "6" => "six", "7" => "seven", "8" => "eight", "9" => "nine" ); print <<MSG; This program will ask you to type in two numbers and then add those nu +mbers together. It will then display the problem and the answer in word form. MSG while (1) { my $user1 = getDigit(4, ' or type done to exit') or next; last if $user1 eq "done"; my $user2 = getDigit(5) or next; my $sum = ($toWord{$user1 + $user2}); $user1 = (ucfirst $toWord{$user1}); print "$user1 plus $toWord{$user2} equals $sum\n"; } sub getDigit { my ($last, $extra) = @_; $extra .= ': '; print "Enter and integer between one and $toWord{$last}$extra"; chomp(my $value = <STDIN>); if ($value !~ /^([1-9]|done)$/) { print "I don't understand '$value'\n"; return; } return $value if $value =~ /^done$/ || $value <= $last; print "$toWord{$value} is not in the range one to $toWord{$last}.\ +n"; return; }
Note that variables are declared where they are first used.
In reply to Re: Subroutine Question
by GrandFather
in thread Subroutine Question
by Socrates440
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |