【问题标题】:How to convert a perl variable in a operator for make equations?如何将运算符中的 perl 变量转换为 make 方程?
【发布时间】:2018-07-13 13:44:18
【问题描述】:
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

我有这段代码,我想将 '$func' 作为运算符来添加 '$numA' 和 '$numB'。

【问题讨论】:

  • 你也可以试试这个my $result = eval("$numA $func $numB"); 但不推荐

标签: function perl variables operator-keyword equation


【解决方案1】:

表达式已经解析很方便。

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

my ($operand1, $operand2, $operator) = @ARGV;

say $ops{$operator}->($operand1, $operand2);

【讨论】:

    猜你喜欢
    • 2010-10-14
    • 2010-09-28
    • 2017-01-17
    • 1970-01-01
    • 2014-09-01
    • 2012-09-22
    • 2017-05-30
    • 1970-01-01
    相关资源
    最近更新 更多