TASK #1: Fractional Addition Substraction
You are given a string representing an expression of fraction addition and substraction.
Write a script that returns the calculation result of given expression in string format.
If final result is an integer, change it to the format of fraction that has a denominator 1.
#!/usr/bin/perl use strict; use warnings; # Everything you need is right here in this module! use Math::BigRat; sub calculate_fraction { my ($input, $print) = @_;# Add zero if the expression starts with + or -. $input = "0$input" if $input =~ /^[+-]/;# Split into fractions and operators. my @elements = split /([+-])/, $input;# Convert the first element into a rational number. my $str = Math::BigRat->new(shift @elements);# Process the remaining elements. while (@elements) { my $operator = shift @elements; my $number = Math::BigRat->new(shift @elements); if ($operator eq '+') { $str += $number; } elsif ($operator eq '-') { $str -= $number; } }# Print the result if requested. if ($print) { if ($str->is_int()) { print "Integer: $str\n"; print "\"$str/1\"\n"; } else { print "Not an integer: $str\n"; } } return $str; } # Tests my @expressions = ( "1/2+3/2",# Output: 2/1 "-5/2-3/2",# Output: -4/1 "5/3-5/3",# Output: 0/1 "10/10-1/10+2/5",# Output: 13/10 "1/6+1/6+1/6"# Output: 1/2 ); foreach my $expr (@expressions) { print "Expression: $expr\n"; calculate_fraction($expr, 1); print "------------------\n"; }