package Wordy; use strict; use warnings; use Exporter qw; our @EXPORT_OK = qw; ######################################################################## # PLEASE NOTE: This solution, as posted, passes all test conditions # # except #15 which tests whether "What is -3 plus 7 multiplied by -2?" # # returns `-8` as order of operations are to be ignored. My solution, # # which does respect order of operations, returns `-17`, which causes # # the test case to fail but I am marking it "Complete" nonetheless. # ######################################################################## my $pattern = qr/(-?\d+|plus|minus|divided|multiplied)/; # to parse input my $op_regex = qr/plus|minus|divided|multiplied/; # valid operations sub answer { my ($question) = @_; # if input does not begin with "What is": die "unknown operation" if ($question !~ m/^What is/); # find all operands and operations based on $partern and store in @m my @m = ($question =~ m/$pattern/g); die "syntax error" unless (scalar @m); # no operands or operations if (scalar @m == 1) { if ($question =~ m/-?\d+\?/) { # 1 operand with no operation return $m[0]; } else { die "unknown operation"; # 1 operand with unknown operation } } my @stack; foreach my $i (0 .. $#m) { # check whether odd indices contain valid operation die "syntax error" if ($i%2 && $m[$i] !~ m/$op_regex/); push @stack => # ? if true : else $m[$i] =~ m/-?\d+/ ? $m[$i] : $m[$i] eq 'plus' ? '+' : $m[$i] eq 'minus' ? '-' : $m[$i] eq 'divided' ? '/' : '*' ; } my $result = eval join ' ', @stack; # trap error in $@, if any die "syntax error" if $@; return $result; } 1;