CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Executing Expression in Perl Script

 



Raj_hpking
Novice

Jul 22, 2014, 2:34 AM

Post #1 of 3 (270 views)
Executing Expression in Perl Script Can't Post

Hi Perl Expert,

I have just started working on Perl. Would like to know how can we execute expression in the Perl Script. Below is scenario,

Suppose I have stored express " (A + (B+C)/100) + D)" in the database. I want to fetch this expression and by dynamically replacing A, B, C & D with their values want to execute it.

Summary: My executable expression is stored in database, I want to fetch it replace constant and execute the same in Perl.

How can I achieve the same.


BillKSmith
Veteran

Jul 22, 2014, 5:39 AM

Post #2 of 3 (265 views)
Re: [Raj_hpking] Executing Expression in Perl Script [In reply to] Can't Post

Fetch your variables and corresponding values into a hash.

Fetch your expression into a string.

Use a regular expression to substitute in the values.

Use the function 'eval' to evaluate the numeric expression.

If valid, print the result.

The following code assumes that you have successfully completed the first two steps. Note: The expression that you posted is not valid. I have removed one parenthesis to 'fix' it.


Code
use strict; 
use warnings;
my %values = (
'A' => 10,
'B' => 12,
'C' => 14,
'D' => .5,
);
my $expression = '(A + (B+C)/100) + D';
my $numeric = $expression =~ s/([ABCD])/$values{$1}/gre;
my $answer = eval $numeric;
if ($@) {
warn "Syntax error in $expression\n";
}
else {
print "$expression = $answer\n";
}

Good Luck,
Bill


Raj_hpking
Novice

Jul 23, 2014, 3:30 AM

Post #3 of 3 (234 views)
Re: [BillKSmith] Executing Expression in Perl Script [In reply to] Can't Post


In Reply To
Fetch your variables and corresponding values into a hash.

Fetch your expression into a string.

Use a regular expression to substitute in the values.

Use the function 'eval' to evaluate the numeric expression.

If valid, print the result.

The following code assumes that you have successfully completed the first two steps. Note: The expression that you posted is not valid. I have removed one parenthesis to 'fix' it.


Thanks a lot Bill,

This is exactly I was looking for.

How can I mark it as Answer. :)

(This post was edited by Raj_hpking on Jul 23, 2014, 3:32 AM)

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives