1

我意识到问题名称并不能说明太多,但我真的不知道如何简短地解释它,所以这里是长版本。

首先,这是我当前的代码:

#! /usr/bin/perl

use strict;
use warnings;

my $input;
while (<>) {
        $input .= $_;
}
$input =~ s/ |\n//g;

print "\n";

我想做的是做一个计算器,例如当用户这样做时,echo "8 * 5 + 21-15" | calculate它会正确计算。所以这是我的思想进展。首先,我将字符串作为一个整体并将其去除所有空白字符。然后我想索引()它是否出现*,+,/或-。然后我想将任何这些运算符之前的所有字符添加到字符串,然后(int)字符串,然后对运算符之后的部分执行相同操作,然后在它们之间进行操作。但我实际上并没有太多关于如何做到这一点的线索。另外,我对 Perl 很陌生(3 天经验),所以如果可能的话,请慢慢来。

非常感谢。

4

1 回答 1

0

If you can accept that your calculator won't be able to handle parenthesis, use a regular expression to parse the string for you:

#!/usr/bin/env perl
use strict;
use warnings;

my @tokens = <STDIN> =~ /(\d+|\+|-|\*|\/)/g;
print "$_\n" for @tokens;

this will provide you with an array of tokens that you can work on, so

echo "8 * 5 + 21-15" | script.pl

will print

8
*
5
+
21
-
15

Now it's up to you to write some code that does the right calculations on the tokens. It isn't too hard if you don't try parsing parens, but if you do, you'll need to write a recursive parser, which is much harder.

于 2012-04-21T19:49:10.463 回答