in reply to Parsing Math Strings

You could go one of two ways: The first is to use Parse::RecDescent to create a math grammar to develop an expression tree that you can evaluate numerous ways. However, this is probably the more difficult way to go.

The better solution is to selectively use eval. Set up a hash that will store variable values. Use a regex to translate 'bare' variables in your expressions to point to this hash. Then eval the expression as necessary:

my $exp = "y=2*x+3"; my %vars = ( x => 1 ); $exp =~ s/([a-z]+)/\$vars{\1}/g; eval $exp; print $vars{ y };

-----------------------------------------------------
Dr. Michael K. Neylon - mneylon-pm@masemware.com || "You've left the lens cap of your mind on again, Pinky" - The Brain
"I can see my house from here!"
It's not what you know, but knowing how to find it if you don't know that's important

Replies are listed 'Best First'.
Re: Re: Parsing Math Strings
by japhy (Canon) on Dec 06, 2001 at 20:46 UTC
    If you're not up to the Parse::RecDescent challenge, you can download the code used in chapter 6 ("Global Matching") of my book. Specifically, from 6.6, "Parsing a language". The code is in examples 6.6 and 6.7. It implements a simple calculator with variable support.

    _____________________________________________________
    Jeff[japhy]Pinyan: Perl, regex, and perl hacker.
    s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;

Re: Re: Parsing Math Strings
by Zaxo (Archbishop) on Dec 07, 2001 at 06:52 UTC

    Another possibility is Math::Expr.

    After Compline,
    Zaxo