use strict;
use warnings;
while (<DATA>) {
chomp;
next unless length;
print "$_ is not a number that I can handle\n" unless /^\d+$/;
print "$_ = ", toWords("00$_"), "\n";
}
sub toWords {
my ($leftBit, $groups) = @_;
return '' unless $leftBit;
$groups ||= 0;
my $group = substr $leftBit, -3, 3, '';
return toWords ($leftBit, $groups + 1) unless $group;
if ($groups > 4) {
print "Argh, I can't deal with numbers that big!\n";
print "The part I can deal with is: ";
return '';
}
my %digits = (
0 => '', 1 => 'one ', 2 => 'two ', 3 => 'three ', 4 => 'four '
+,
5 => 'five ', 6 => 'six ', 7 => 'seven ', 8 => 'eight ', 9 =>
+'nine '
);
my %teens = (
10 => 'ten ', 11 => 'eleven ', 12 => 'twelve ', 13 => 'thirtee
+n ',
14 => 'fourteen ', 15 => 'fifteen ', 16 => 'sixteen ',
17 => 'seventeen ', 18 => 'eighteen ', 19 => 'nineteen '
);
my %tens = (
2 => 'twenty ', 3 => 'thirty ', 4 => 'fourty ',
5 => 'fifty ', 6 => 'sixty ', 7 => 'seventy ',
8 => 'eighty ', 9 => 'ninety '
);
my $groupStr = '';
# Deal with last two digits
my $tensStr = $group % 100;
$groupStr = $tens{int ($tensStr / 10)} if $tensStr >= 20;
if (int ($tensStr / 10) == 1) {
$groupStr .= $teens{int $tensStr};
} else {
$groupStr .= $digits{$tensStr % 10}
unless $tensStr > 10 and $tensStr % 10 == 0;
}
my $hundreds = int ($group / 100);
if ($hundreds) {
my $prefix = "$digits{$hundreds}hundred ";
$prefix .= 'and ' if $groupStr;
$groupStr = "$prefix$groupStr";
}
my $prefix = toWords ($leftBit, $groups + 1);
$prefix .= qw(thousand million billion trillion)[$groups] . ' ' if
+ $prefix;
$groupStr = "$prefix$groupStr";
$groupStr = 'zero' unless $groupStr or $groups;
return $groupStr;
}
__DATA__
0
1
10
11
20
21
99
100
901
98012785623123
Prints:
0 = zero
1 = one
10 = ten
11 = eleven
20 = twenty
21 = twenty one
99 = ninety nine
100 = one hundred
901 = nine hundred and one
98012785623123 = ninety eight trillion twelve billion seven hundred an
+d eighty five million six hundred and twenty three thousand one hundr
+ed and twenty three
looks recursive to me, but it would be easy to make it iterative instead (left as an exercise for the reader).
DWIM is Perl's answer to Gödel