Hi respected monks!
I've written a calculated script just for fun.Below is my code:
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";
my question is:
Could I change a string to a mathematics expression directly?So I needn't change (* / + -) to arithmetic operator one by one.
Thanks in advance!
UPDATE: Thank liverpole,and correct some ridiculous mistakes.
I am trying to improve my English skills, if you see a mistake please feel free to reply or /msg me a correction