Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
• Status: Solved
• Priority: Medium
• Security: Public
• Views: 196

# Scalar input / convert to operator

I have three arguments on the command line. One of which is a mathematical operator, such as +. I'm parsing the arguments to three scalars. How can I use the scalar as an math operator?
IE: \$result = (\$operand \$operator \$operand) ?  \$result = (\$operand + \$operand).  Thanks!
davidt@t-online.de
0
kenai
• 2
1 Solution

Commented:
if( \$operator eq "+" ) {
.....
} else if( \$operator eq "-" ) {
}

i sense that what you're asking is not available in a language like Perl but is found in functional languages such LISP (you could construct a list and since every list is actually a statement of the form (operator operand1 operand2 ... operandN) you could execute it....

I dont think this is available in Perl....

Hope this helps....
0

Commented:
it could be done as an eval but it's much easier and safer just to make a separate case for each operator, as azawawi shows above
0

Commented:
playing with lists & functions is a game than LISP (and its dialects) do well....
0

Commented:
#you could do
\$result = eval "\$operand \$operator \$operand";
#but that could be dangerous if you allow someone to set something like
\$operator = ',system("delete *.*"),'

#it may be safer to use  something like
\$result = &{\${{
'+' => sub {\$_[0] + \$_[1]},
'-' => sub {\$_[0] - \$_[1]},
'*' => sub {\$_[0] * \$_[1]},
'/' => sub {\$_[0] / \$_[1]},
}}{\$operand}||sub{undef}}(\$operand,\$operand);
0

## Featured Post

• 2
Tackle projects and never again get stuck behind a technical roadblock.