![]() |
|
|||||||
| Programming C, bash, Python, Perl, PHP, Java, you name it. |
![]() |
|
|
Thread Tools | Display Modes |
|
|
|
|||
|
Hi,
Trying to solve a problem with either the eval or s///e functions, and I haven't succeeded yet. I want to store an expression/equation in mysql. The expression contains the perl variable names. At runtime, I retrieve the record into a variable. And I evaluate the expression with the variables' current values. something like Code:
my $a;
my $b;
my $c;
my $result;
my $row;
# do stuff. in the process setting $a = 5, $b = 6, $c = 2
...
# at this point assume $a = 5, $b = 6, $c = 2, expression: '($a * $b) / $c'
$statement->execute($parm);
$row = $statement->fetchrow_hashref();
$result = s//$row->{'expression'}/e;
# here i want perl to see there are variables in $row->{'expression'}, and
# substitute the current values of those variables, and
# calculate so that $result == 15.
Any perl expertise much appreciated! TIA |
|
|||
|
I may have found the answer here:
http://www.arl.wustl.edu/projects/fp...og/ch05_01.htm ex. Code:
# put some code inside $str $str = '$c = $a + $b'; # Perl doesn't care what's inside $str $a = 10; $b = 20; eval $str; # Treat $str as code, and execute it. print $c; # prints 30 |
|
||||
|
Generally whenever you want to execute a string or stored exppression like that as a statement, look for a function named eval or something comparable in the language. Programmers and language creators alike are lazy beasts: they often choose the same names for things, just look at how many languages have a print thingy ;-).
Do be mindful though, that when you do eval $str you are basically saying: local $@; { put $str here as if I wrote it myself and set $@ to contain any exception from perl. } So be warey of what you eval EXPR. You wouldn't want to execute eval(`rm -rf /var/db/mysql`) now would you? If you've got a lot of evals to do, you should also note that eval is slow.
__________________
My Journal Thou shalt check the array bounds of all strings (indeed, all arrays), for surely where thou typest ``foo'' someone someday shall type ``supercalifragilisticexpialidocious''. Last edited by TerryP; 16th February 2009 at 06:49 AM. |
|
|||
|
Quote:
Likewise, it is better to find out early that an error has occurred rather than wait until later when the culprit has been masked many times over. |
![]() |
| Thread Tools | |
| Display Modes | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| C/C++ Syntax highlighting in emacs | rex | FreeBSD General | 1 | 12th October 2008 03:21 AM |
| PHP regular expression help | cajunman4life | Programming | 2 | 16th August 2008 05:17 PM |
| Syntax Highlighting | JMJ_coder | Programming | 17 | 22nd June 2008 02:24 PM |
| I need help with make.conf syntax | troberts | FreeBSD Ports and Packages | 4 | 1st June 2008 03:58 AM |
| Vi type syntax applications | corey_james | Off-Topic | 9 | 28th May 2008 04:15 PM |