Betterthanyoda56
Betterthanyoda56

Reputation: 31

Conditional Statement giving seemingly wrong answer: What am I missing

So I have to make a simple calculator in Perl that maintains an accumulator and does simple operations. The accumulator starts at 0 and then changes based on the results that I receive. At the moment I am only trying to get addition to work. When I check to ensure that the operator entered is + something goes wrong. For instance:

Accumulator: 0
Operator: Anything put here results in addition. Including this sentence.
Operand: 4

Accumulator: 4

It catches numbers but nothing else. I have tried using grep and a list of the operators. I have exhausted all of my ideas. Here is my code (Fyi first post so help me with any noob errors):

my $running = 1;
my $accum = "0";
my $operator;
my $operand;

print("Welcome to the simple, command line calculator.\n");
print("To terminate, press Control-C.\n\n");

while ($running){

    print("\nAccumulator: ".$accum."\n");
    print("Operator: ");
    $operator = <STDIN>;
    if ($operator == "+"){
            print("Operand: ");
            operand = <STDIN>;
            $accum += $operand;
    }
    else{
        print("Invalid operator: ".$operator."\n");
    }
}

Upvotes: 3

Views: 213

Answers (2)

geekosaur
geekosaur

Reputation: 61369

Perl doesn't remove the ending newline from input unless you use the -l option, so you're comparing "+" against "+\n". Usually you want to do soemthing like chomp($operator);.

That said, your real problem is that == does numeric comparison, and both "+" and "+\n" evaluate to 0 in numeric context. (Using -w, as you should always do, would warn you about this.) Use the eq operator for string comparison.

Upvotes: 13

bdonlan
bdonlan

Reputation: 231153

== compares numbers, not strings. If you compare strings, the strings will be converted to numbers; for non-numeric strings, this means they become 0. So $operator == "+" becomes 0 == 0.

For strings, use eq instead. Additionally, keep in mind that <STDIN> will preserve newlines; make sure to chomp $operator as well.

Upvotes: 3

Related Questions