Sha256: a33f77e1eea7c58e184949c6f5febc8b3b5e4a10c9e85558a9e7df96f99a7d1d
Contents?: true
Size: 802 Bytes
Versions: 73
Compression:
Stored size: 802 Bytes
Contents
package Wordy; use strict; use warnings; my %operators = ( 'minus' => '-', 'plus' => '+', 'divided by' => '/', 'multiplied by' => '*', ); my $OPERATORS = join '|', keys %operators; my $NUMBER = qr/[\d-]+/; sub answer { my ($str) = @_; if ($str =~ m{^What\s+is\s+((?:$NUMBER\s+($OPERATORS)\s+)+$NUMBER)\s*\?}) { my $expression = $1; $expression =~ s/($OPERATORS)/$operators{$1}/g; # it seems the expressions are always left associative so: #return eval $expression; my @parts = split /\s+/, $expression; while (@parts > 2) { my ($x, $op, $y, @leftover) = @parts; @parts = (eval("$x $op $y"), @leftover); } return shift @parts; } die "ArgumentError"; } 1;
Version data entries
73 entries across 73 versions & 1 rubygems