-
Notifications
You must be signed in to change notification settings - Fork 314
/
ch-2.pl
executable file
·64 lines (52 loc) · 870 Bytes
/
ch-2.pl
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#! /usr/bin/perl
use strict;
use warnings;
my @stack=();
my %op=(
add => \&add,
'+' => \&add,
sub => \&sub,
'-' => \&sub,
mul => \&mul,
'*' => \&mul,
div => \&div,
'/' => \&div,
neg => \&neg,
dup => \&dup,
pop => \&pop,
exch => \&exch,
);
foreach my $p (@ARGV) {
if (exists $op{$p}) {
$op{$p}->();
} elsif ($p =~ /^[.0-9]+$/) {
push @stack,$p;
} else {
die "Unknown input $p\n";
}
print join(' ',@stack),"\n";
}
sub add {
push @stack,(pop @stack) + (pop @stack);
}
sub sub {
push @stack,-((pop @stack) - (pop @stack));
}
sub mul {
push @stack,(pop @stack) * (pop @stack);
}
sub div {
push @stack,1/((pop @stack) / (pop @stack));
}
sub neg {
push @stack,-(pop @stack);
}
sub dup {
push @stack,$stack[-1];
}
sub pop {
pop @stack;
}
sub exch {
($stack[-1],$stack[-2])=($stack[-2],$stack[-1]);
}