I have a question, and I think the answer will clear up a lot aobut subroutines for me. I am writing a program that asks for a simple addition problem, stores the integers for the addition problem in variables, converts them to words, and displays the problem and the answer in word form. I call the same subroutine for the second integer as I do for the sum, but the subroutine only works for first integer. It doesn't return anything for the sum. Can anybody tell me why?
#!/usr/bin/perl -w
use strict ;
my (@a, $userin, $userin2, $sum) ;
@a = (1 .. 9) ;
print "This program will ask you to type in two numbers and then add t
+hose numbers together.\nIt will then display the problem and the answ
+er in word form.\n" ;
$userin = 0 ;
while ($userin ne "done") {
print "Type in a single digit number between one and four, or type
+ done to exit.\n" ;
chomp ($userin = <STDIN>) ;
if ($userin eq "done") {
last ;
}
print "Type in a single digit number between one and five\n" ;
chomp ($userin2 = <STDIN>) ;
if (($userin =~ /^[^1-4]$/) || ($userin2 =~ /^[^1-5]$/)) {
print "I do not understand\n" ;
}
else {
$sum = ($userin + $userin2) ;
$userin = (firstnumtoword($userin)) ;
$userin2 = (numtoword($userin2)) ;
$sum = (numtoword($sum)) ;
print "$userin plus $userin2 equals $sum\n" ;
}
}
sub numtoword {
$_ = shift ;
my (%nums) ;
%nums = ("1"=>"one", "2"=>"two", "3"=>"three", "4"=>"four", "5"=>"
+five", "6"=>"six", "7"=>"seven", "8"=>"eight", "9"=>"nine") ;
return $nums{$userin2} ;
}
sub firstnumtoword {
$_ = shift ;
my (%nums2) ;
%nums2 = ("1"=>"One", "2"=>"Two", "3"=>"Three", "4"=>"Four", "5"=>
+"Five", "6"=>"Six", "7"=>"Seven", "8"=>"Eight", "9"=>"Nine") ;
return $nums2{$userin2} ;
}
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.