Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a perl variable in a operator for make equations?

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

I have this code and I want to get '$func' as an operator to add '$numA' with '$numB'.

like image 378
Leandro Matilla Avatar asked Jan 18 '26 13:01

Leandro Matilla


1 Answers

It's convenient that the expression is already parsed.

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

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

say $ops{$operator}->($operand1, $operand2);
like image 60
ikegami Avatar answered Jan 20 '26 05:01

ikegami