15giftsTask/number_generator.pl
2023-11-14 12:01:44 +01:00

107 lines
3.2 KiB
Perl

#!/usr/bin/env perl
use v5.36.0;
use strict;
use warnings;
use feature 'signatures';
my @numbers_one_to_nine = qw/one two three four five six seven eight nine/;
my @numbers_one_to_nineteen = (@numbers_one_to_nine, qw/ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen/);
my @decenes = (undef, qw/twenty thirty forty fifty sixty seventy eighty ninety/);
sub main {
my $number = $ARGV[0];
if (!defined $number) {
$number = 1_111_111;
}
say convert_number_to_words($number)
}
sub convert_number_to_words($number) {
my $return = '';
{
if ($number < 1) {
$return .= 'zero';
last;
}
append_millions_to_return(\$number, \$return);
append_thousand_hundreds(\$number, \$return);
append_decene_thousands(\$number, \$return);
append_hundred(\$number, \$return);
append_decene(\$number, \$return);
}
$return =~ s/(\w)/\U$1/;
$return .= '.';
return $return;
}
sub append_decene($number_ref, $return_ref) {
my $number = ${$number_ref};
my $decene = int ($number / 1);
return if ($decene < 1);
${$return_ref} .= ' and ' if length ${$return_ref};
${$return_ref} .= convert_two_chars_number_to_words($decene);
${$number_ref} = 0;
}
sub append_decene_thousands($number_ref, $return_ref) {
my $number = ${$number_ref};
my $thousand_decene_unit = int ($number / 1_000);
if (length ${$return_ref} > 0 && $thousand_decene_unit < 1) {
${$return_ref} .= ' thousand';
};
return if ($thousand_decene_unit < 1);
${$return_ref} .= ' and ' if length ${$return_ref};
${$return_ref} .= convert_two_chars_number_to_words($thousand_decene_unit) . ' thousand';
${$number_ref} = $number % 1_000;
}
sub append_hundred($number_ref, $return_ref) {
my $number = ${$number_ref};
my $hundred = int ($number / 100);
return if ($hundred < 1);
${$return_ref} .= ', ' if length ${$return_ref};
${$return_ref} .= $numbers_one_to_nine[$hundred-1] . ' ' . 'hundred';
${$number_ref} = $number % 100;
}
sub convert_two_chars_number_to_words($number) {
my $return = '';
{
if ($number < 20) {
$return .= $numbers_one_to_nineteen[$number-1];
last;
}
my $decene = int($number / 10);
$return .= $decenes[$decene-1];
my $unit = $number % 10;
if ($unit < 1) {
last;
}
$return .= '-';
$return .= $numbers_one_to_nine[$unit-1];
}
return $return;
}
sub append_thousand_hundreds($number_ref, $return_ref) {
my $number = ${$number_ref};
my $thousand_hundreds_unit = int ($number / 100_000);
return if ($thousand_hundreds_unit < 1);
${$return_ref} .= ', ' if length ${$return_ref};
${$return_ref} .= $numbers_one_to_nine[$thousand_hundreds_unit-1] . ' ' . 'hundred';
${$number_ref} = $number % 100_000;
}
sub append_millions_to_return($number_ref, $return_ref) {
my $number = ${$number_ref};
my $millions_unit = int ($number / 1_000_000);
return if ($millions_unit < 1);
${$return_ref} .= $numbers_one_to_nine[$millions_unit-1] . ' ' . 'million';
${$number_ref} = $number % 1_000_000;
}
main()