The weekly challenge 227 - Task 2: Roman Maths

 1 #!/usr/bin/perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-227/#TASK2
 3 #
 4 # Task 2: Roman Maths
 5 # ===================
 6 #
 7 # Write a script to handle a 2-term arithmetic operation expressed in Roman numeral.
 8 #
 9 # Example
10 #
11 # IV + V     => IX
12 # M - I      => CMXCIX
13 # X / II     => V
14 # XI * VI    => LXVI
15 # VII ** III => CCCXLIII
16 # V - V      => nulla (they knew about zero but didn't have a symbol)
17 # V / II     => non potest (they didn't do fractions)
18 # MMM + M    => non potest (they only went up to 3999)
19 # V - X      => non potest (they didn't do negative numbers)
20 #
21 ############################################################
22 ##
23 ## discussion
24 ##
25 ############################################################
26 #
27 # We use the Roman module from CPAN to convert from/to Roman
28 # numbers. The rest is handling the operand and the special
29 # cases for the results
30 #
31 use strict;
32 use warnings;
33 use Roman;
34 
35 roman_maths("IV", "+", "V");
36 roman_maths("M", "-", "I");
37 roman_maths("X", "/", "II");
38 roman_maths("XI", "*", "VI");
39 roman_maths("VII", "**", "III");
40 roman_maths("V", "-", "V");
41 roman_maths("V", "/", "II");
42 roman_maths("MMM", "+", "M");
43 roman_maths("V", "-", "X");
44 
45 sub roman_maths {
46    my ($num1, $oper, $num2) = @_;
47    print "Input: $num1 $oper $num2\n";
48    $num1 = arabic($num1);
49    $num2 = arabic($num2);
50    my $result;
51    eval "\$result = $num1 $oper $num2;";
52    die "eval error $@" if $@;
53    if($result != int($result)) {
54       print "Output: non potest\n";
55    } elsif ( $result < 0 ) {
56       print "Output: non potest\n";
57    } elsif ( $result > 3999 ) {
58       print "Output: non potest\n";
59    } elsif ( $result == 0) {
60       print "Output: nulla\n";
61    } else {
62       print "Output: " . uc(roman($result)) . "\n";
63    }
64 }