aboutsummaryrefslogtreecommitdiff
path: root/challenge-039/e-choroba/perl5/ch-2.pl
blob: c51389d5a821b9330849e352815dee691e84d041 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };
use utf8;

my %op = ( '+' => sub { $_[0] + $_[1] },
           '−' => sub { $_[0] - $_[1] },
           '×' => sub { $_[0] * $_[1] },
           '÷' => sub { $_[0] / $_[1] });

sub rpn {
    my ($input) = @_;
    my @tokens = split ' ', $input;
    my @stack;
    for my $token (@tokens) {
        if ($token =~ /^[0-9]+$/) {
            push @stack, $token;
        } else {
            push @stack, $op{$token}->(((pop @stack) // die 'Stack empty'),
                                       (pop @stack) // die 'Stack empty');
        }
    }
    my $result = pop @stack;
    die "Left on stack: @stack" if @stack;

    return $result
}

my $input = '15 7 1 1 + − ÷ 3 × 2 1 1 + + −';
my $expected_result = 5;
my $result = rpn($input);
die unless $result == $expected_result;
say $result;