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.

True laziness is hard work

In reply to Re: Subroutine Question by GrandFather
in thread Subroutine Question by Socrates440

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.