aboutsummaryrefslogtreecommitdiff
path: root/challenge-047/user-person/perl/ch-1.pl
blob: ec2e27b494aa89e1103228f878fd315d24f67028 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#!/usr/bin/env perl

###########################################################################
# script name: ch-1.pl                                                    #
#                                                                         #
# https://perlweeklychallenge.org/blog/perl-weekly-challenge-047/         #
#                                                                         #
# Write a script that accepts two roman numbers and operation. It should  #
# then perform the operation on the give roman numbers and print the      #
# result.                                                                 #
#                                                                         #
# e.g.                                                                    #
#         ch-1.pl V + VI                                                  #
#                                                                         #
# output:                                                                 #
#         XI                                                              #
#                                                                         #
###########################################################################

use strict;
use warnings;

use FindBin;
use Roman;

my $argString = uc "@ARGV";
my $script    = $FindBin::Script;

die "$FindBin::Script requires arguments.\n" if scalar @ARGV == 0;

print STDERR "[Arabic number detected in input]\n" if $argString =~ m{\d+};

$argString =~ s{(\s*[-+*/%]\s*)}{ $1 }g;
$argString =~ s{([MDCLXVI]+)}{arabic $1}ge;

my $result = eval $argString;

my $oldResult = $result;
$result = int $result;
my $decimal = $oldResult - $result;
print STDERR "Calculation result had a decimal $decimal that was truncated.\n" if $decimal;

if ( $result == 0) {
    print "N (no formal zero)\n"; # https://en.wikipedia.org/wiki/Roman_numerals#Zero
} elsif ($result > 3_999) {
    die "Calculation result $result exceeds MMMCMXCIX (3,999) the maximum value of the Roman number format.\n";
} elsif ($result < 0) {
    die "Calculation result $result is negative. Roman numbers are positive integers.\n";
} else {
    $result = Roman(int $result);
    print "$result\n";
}