Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: '+' to +

by monarch (Priest)
on May 29, 2005 at 12:16 UTC ( [id://461501]=note: print w/replies, xml ) Need Help??


in reply to '+' to +

I'm sure there are better ways than the one I'm about to suggest.

Firstly you've used a regexp to clean up the input, very good, you're protecting yourself against potentially nasty input from the source.. because real-world programmers know real-world people try and stick anything into our machines!

Perhaps you could make the regexp ensure the operator is only one of the four specified operations and then performing an eval on the reconstructed operation?

e.g.

$Problem =~ /(\d+) # one or more digits \s* # zero or more whitespace ([-+\/*]) # operator (1 char only) \s* # zero or more whitespace (\d+)/x; # one or more digits my $Number1 = $1; my $Number2 = $3; my $Operator = $2; my $Answer; my $Code = "$1 $2 $3"; # we're confident this is safe $Answer = eval "$Code";

Of course if statements should be littered about to ensure the regexp actually matches etc.

Update: as wfsp pointed out below I have now escaped the forward slash in the regexp because the forward slash is the regexp delimiter.

Replies are listed 'Best First'.
Re^2: '+' to +
by nobull (Friar) on May 29, 2005 at 12:47 UTC
    Perhaps you could make the regexp ensure the operator is only one of the four specified operations and then performing an eval on the reconstructed operation?

    I agree about laundering the input but I'd want to check that the whole input matches the expected pattern.

    if ( my ($Code) = $Problem =~ /^\s*(\d+\s*[-+/*]\s*\d+)\s*=\s*$/ ) { if ( defined ( my $Answer = eval $Code ) ) { # do stuff with $Answer } else { # do stuff with $@ } } else { # Complain about invalid format }

    I'd even tend to be a bit more liberal with my laundering to let though any simple arithmetic /^([-+/*\s\d().]+)=\s*$/.

Re^2: '+' to +
by NateTut (Deacon) on May 29, 2005 at 14:11 UTC
    I should explain that this snippet is from a little client/server math game I'm writing for my kids to practice their math skills. Therefore I know the format of $Problem precisely because I generated it in the game server. That's why I didn't bother with a lot of validation.

    What I am looking for is a cool way to convert the string '+' to the operator +.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://461501]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (5)
As of 2024-04-19 12:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found