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.139 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.138 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.137 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.136 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.135 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.134 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.133 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.132 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.131 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.130 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.129 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.128 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.127 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.126 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.125 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.124 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.123 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.122 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.121 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm
trackler-2.2.1.120 tracks/perl5/exercises/wordy/.meta/solutions/Wordy.pm