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.159 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.158 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.157 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.156 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.155 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.154 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.153 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.152 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.151 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.150 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.149 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.148 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.147 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.146 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.145 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.144 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.143 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.142 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.141 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.140 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm