Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
Solved

# Scalar input / convert to operator

Posted on 2000-04-16
Medium Priority
194 Views

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
Question by:kenai
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
• 2

LVL 2

Accepted Solution

azawawi earned 150 total points
ID: 2720477
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

LVL 4

Expert Comment

ID: 2720833
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

LVL 2

Expert Comment

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

LVL 84

Expert Comment

ID: 2721703
#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

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Email validation in proper way is  very important validation required in any web pages. This code is self explainable except that Regular Expression which I used for pattern matching. I originally published as a thread on my website : http://www…
There are many situations when we need to display the data in sorted order. For example: Student details by name or by rank or by total marks etc. If you are working on data driven based projects then you will use sorting techniques very frequently.…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Six Sigma Control Plans
###### Suggested Courses
Course of the Month7 days, 5 hours left to enroll