Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Use operator stored in a variable?

Status
Not open for further replies.

CJason

Programmer
Oct 13, 2004
223
US
Say:
Code:
$add = '+';
$a = 1;
$b = 2;
Is it possible to add a & b together, using the variable $add as the operator? Like:
Code:
$total = $a $add $b;
Obviously, what I have written here doesn't work, but is there a way to make this work? If so, any clues would be appreciated! Thanks!
 
One way:

Code:
$add = '+';
$a = 1;
$b = 2;
$total = eval "$a $add $b";
print $total;

Make sure $add is validated if the input comes from outside the script, otherwise it is possible to insert other code into the program and eval will happily execute it.


------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top