Re: converting text expressions (like "1+1") to values
- From: daizisheng@xxxxxxxxx (Daizisheng)
- Date: Sat, 29 Dec 2007 00:41:08 -0800 (PST)
On Dec 29, 2:50 am, chas.ow...@xxxxxxxxx (Chas. Owens) wrote:
On Dec 28, 2007 10:15 AM, Adarsh Srivastava<Adarsh.Srivast...@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};"
I am wondering if there are some methods which can let us free from
such things.
I mean if there is an embedded solution which can refuse unlink
function but accept normal (like math) functions?
thanks
.
- References:
- Re: converting text expressions (like "1+1") to values
- From: Chas. Owens
- Re: converting text expressions (like "1+1") to values
- Prev by Date: Re: configuring startperl during make ?
- Next by Date: Handling errors when working with files
- Previous by thread: Re: converting text expressions (like "1+1") to values
- Next by thread: Re: converting text expressions (like "1+1") to values
- Index(es):
Relevant Pages
|
|