需要明确的是,您不是在寻找常规计算器。您正在寻找一个打破数学规则的计算器。
您想要的是提取操作数和运算符,然后同时处理它们 3 个,第一个是滚动“和”,第二个是运算符,第三个是操作数。
处理它的简单方法是只使用eval 字符串。但是由于eval 是一个危险的操作,我们需要对输入进行去污点。我们通过正则表达式匹配来做到这一点:/\d+|[+\-*\/]+/g。这匹配 1 个或多个 + 数字 \d 或 |,1 个或多个 + 或 +-*/。我们会尽可能多地进行此匹配/g。
use strict;
use warnings;
use feature 'say';
while (<>) { # while we get input
my ($main, @ops) = /\d+|[+\-*\/]+/g; # extract the ops
while (@ops) { # while the list is not empty
$main = calc($main, splice @ops, 0, 2); # take 2 items off the list and process
}
say $main; # print result
}
sub calc {
eval "@_"; # simply eval a string of 3 ops, e.g. eval("1 + 2")
}
您可能希望添加一些输入检查,以计算 args 并确保它们是正确的数字。
一个更明智的解决方案是使用调用表,使用运算符作为键,从设计用于处理每个数学运算的子哈希中:
sub calc {
my %proc = (
"+" => sub { $_[0] + $_[1] },
"-" => sub { $_[0] - $_[1] },
"/" => sub { $_[0] / $_[1] },
"*" => sub { $_[0] * $_[1] }
);
return $proc{$_[1]}($_[0], $_[2]);
}
只要中间参数是一个运算符,这将执行所需的操作,而不需要eval。这也将允许您添加将来可能需要的其他数学运算。