Lea*_*lla 3 variables perl equation function operator-keyword
my $numA= $ARGV[0]; #5
my $numB= $ARGV[1]; #5
my $func= $ARGV[2]; #+
my $result = $numA .$func . $numB; #The result shoudl be 10
print "The result is: $result"; # The result is: 5+5
Run Code Online (Sandbox Code Playgroud)
我有这个代码,我希望'$ func'作为运算符添加'$ numA'和'$ numB'.
表达式已被解析很方便.
my %ops = (
'+' => sub { $_[0] + $_[1] },
'-' => sub { $_[0] - $_[1] },
'*' => sub { $_[0] * $_[1] },
'/' => sub { $_[0] / $_[1] },
);
my ($operand1, $operand2, $operator) = @ARGV;
say $ops{$operator}->($operand1, $operand2);
Run Code Online (Sandbox Code Playgroud)