使用字符串中的运算符进行计算

时间:2013-09-29 16:53:24

标签: perl

我正在尝试制作一个程序女巫给用户一个随机的数学问题和答案,但如果我尝试将运算符存储在我的数组中而不将它们存在于字符串中,则会出现错误但是当我想要程序时这会导致问题解决问题,因为忽略了运算符并将两个数字相加。请帮忙!?!

    #!/usr/bin/perl

    use strict;
    use warnings;

    sub randomNumber  #generates a random number (1-100)
    {
        my $randomNumber = int(rand(100)) + 1;
        return "$randomNumber\n";
    }

    sub operators #randomly chooses a operator
    {
        my @list = ( "+" , "-" ,  "/"  , "*" );
        my $index = rand(@list);
        return $list[$index];
        }

    sub question{   
        my $firstNumber = randomNumber();
        my $operater = operators();
        my $secondNumber = randomNumber();
        print $firstNumber.$operater.$secondNumber."\n";
        print $firstNumber + $operater + $secondNumber;   #this is the problem line
    }

    question();

Here is a screenshot of the code when run:

感谢您的帮助,这是我为未来读者完成的实施:

#!/usr/bin/perl

use strict;
use warnings;

sub randomNumber
{
    my $randomNumber = int(rand(100)) + 1;
    return $randomNumber;
}

sub randomOperator
{
    my @operators = ( "+" , "-" ,  "/"  , "*" );
    my $index = rand(@operators);
    return $operators[$index];
    }

sub question{   
    my $firstNumber = randomNumber();
    my $operator = randomOperator();
    my $secondNumber = randomNumber();
    print "$firstNumber $operator $secondNumber =";
    my $userAnswer = <STDIN>;
    my $trueAnswer = eval "$firstNumber $operator $secondNumber";  #gets answer
    if ($userAnswer == $trueAnswer)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

print question(); 

2 个答案:

答案 0 :(得分:4)

什么是三个加星号?是的,这没有多大意义,但这就是你要求Perl做的事情

看起来您正在尝试生成并执行Perl代码,但您使用.代替+而不是+来连接字符串。然后你仍然需要将代码传递给Perl进行编译和执行,这可以使用eval EXPR来完成。

my $code = '$firstNumber' . $operater . '$secondNumber';
my $result = eval($code);

而不是生成Perl代码,更强大的解决方案是使用调度表。

my %operations = (
   '*' => sub { $_[0] * $_[1] },
   '/' => sub { $_[0] / $_[1] },
   '+' => sub { $_[0] + $_[1] },
   '-' => sub { $_[0] - $_[1] },
);

my $result = $operations{$operater}->($firstNumber, $secondNumber);

注意:

  • 如果您使用发送表,my @list = ...;将变为my @list = keys(%operations);
  • $operater应命名为$operator
  • @list应命名为@operators
  • operators应命名为randomOperator

答案 1 :(得分:2)

print eval "$firstNumber $operater $secondNumber";

而不是

print $firstNumber + $operater + $secondNumber;

在处理用户输入时,eval之前的完整性检查也是个好主意。