xiaoyafeng has asked for the wisdom of the Perl Monks concerning the following question:
my question is: Could I change a string to a mathematics expression directly?So I needn't change (* / + -) to arithmetic operator one by one.print "Welcome to calculator script!!\n"; print "Please choose calculator range:\n"; print "-100 -- +100 => 1 (default)\n"; print "-10 -- +10 => 2 \n"; print "your choice:"; my $choice = <>; chomp $choice; my @operators = qw(+ - * /); my ($value1,$value2,$true_answer,$answer,$time_cal,$operator); die "error !!! please check $!\n" unless $choice == 1 or $choice == 2; if ($choice == 1) { $value1 = int rand(100); $value2 = int rand(100); } else { $value1 = int rand(10); $value2 = int rand(10); } $operator = $operators[int rand(4)]; $true_answer = $value1 + $value2 if $operator eq $operators[0]; $true_answer = $value1 - $value2 if $operator eq $operators[1]; $true_answer = $value1 * $value2 if $operator eq $operators[2]; $true_answer = int($value1 / $value2) if $operator eq $operators[3]; print "$value1$operator$value2="; $time_cal = time; eval{ $answer = <>; $time_cal = time - $time_cal; die "you are wrong!!!!\n" unless $answer == $true_answer; }; die "please input decimal number!!!!\n" if $@ ; print "you spend $time_cal seconds!!!!\n";
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: string to expression
by liverpole (Monsignor) on Jan 10, 2007 at 02:49 UTC | |
|
Re: string to expression
by GrandFather (Saint) on Jan 10, 2007 at 03:05 UTC | |
by xiaoyafeng (Deacon) on Jan 10, 2007 at 04:51 UTC | |
by ikegami (Patriarch) on Jan 10, 2007 at 06:39 UTC | |
|
Re: string to expression
by mkirank (Chaplain) on Jan 10, 2007 at 03:35 UTC |