Re: converting text expressions (like "1+1") to values



On Dec 28, 2007 10:15 AM, Adarsh Srivastava
<Adarsh.Srivastava@xxxxxxxxxxxxxxxx> wrote:
Hello,

Is there any inbuilt/external function or library that can convert a text
expression (eg. "22 + 23") and evaluate the resulting value?( 45 in this
case).
snip

Well, the string form of eval will do this; however, it is very
dangerous. What if the string contained valid Perl code* to do
something on your system? Any time you use the string form of eval
you should first run the string through a regex make sure it only
contains things you expect it to. If the expressions are simple
arithmetic then this should suffice:

my $expr = get_expression(); #I don't know how you are getting "22 + 23"
die "bad expression: [$expr]" unless $expr =~ m{\A[ 0-9+-/*]+\z};
my $result = eval $expr;
die "got error [$@] when eval'ing [$expr]" if $@;

If you need to be able to call functions like sqrt, your regular
expression will become significantly more complex and it may be time
to look into writing a parser instead (especially if the names, call
signatures, or expected return values of the functions don't line up
with the standard Perl versions).

* imagine eval'ing the string "use File::Find; find sub { unlink }, $ENV{HOME};"
.



Relevant Pages

  • Re: Regular Expression, to use or not to use...
    ... So I have something that will search the string 10x ... Yea thats true, like I said I still use them occasionally, as a hack, ... Also this is an extremly simple re, no |'s or complex expressions. ... >> simple string operations where I can come up with the expression in a ...
    (microsoft.public.dotnet.general)
  • Re: Small confusion about negative lookbehind
    ... > My candidate string is "ab". ... > The expressions I'm testing this string against are the following, ... but the position between characters. ... Regular expressions describe not only strings, ...
    (comp.lang.java.programmer)
  • Re: Why not FP for Money?
    ... >> conversion of binary floats to decimal floats, and the string looks ... >> out of place in numeric expressions. ... > that using 'd' is a compromise to having no way to write ... Carlos Ribeiro ...
    (comp.lang.python)
  • Re: Regular Expression, to use or not to use...
    ... > Expressions for a long time now, ... > external tools to help me with. ... > order of 10 times slower then straight forward string parsing code. ... This could be a result of .NET engine, ...
    (microsoft.public.dotnet.general)
  • RE: speed up string matching
    ... > I need to match an expression and its reverse to a very long string. ... you'd have to merge your expressions somehow - the easiest ... So in order to match a very long string with multiple expressions simultaneously and faster than the matching procedure I have described above I need multiple computers? ...
    (perl.beginners)