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

Version Path
trackler-2.2.1.180 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.179 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.178 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.177 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.176 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.175 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.174 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.173 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.172 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.171 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.170 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.169 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.167 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.166 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.165 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.164 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.163 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.162 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.161 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.160 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm