KingMak
KingMak

Reputation: 1478

Integer Division with Perl in my code doesn't work

In the Perl program below the division of integers doesn't happen for some reason. Instead the console outputs the concatination of the two integers, also the if statement for the divsion doesn't happen either. Why is this? Thanks.

Code:

print "Please Enter Your First Number\n";
$num1 = <>; chomp $num1;

print "Please Enter Your Operation\n";
$operation = <>; chomp $operation;

print "Please Enter Your Second Number\n";
$num2 = <>; chomp $num2;

if ($operation == "+"){
    $result = $num1 + $num2;
} elsif ($operation == "-"){
    $result = $num1 - $num2;
} elsif ($operation == "*"){
    $result = $num1 * $num2;
#Problem HERE:
} elsif ($operation == "/"){
    if ($num2 == 0){
        print "Cant Divide be Zero Mate\n";
    } else {
        $result = $num1 / $num2;
    }
}

print "\n";
print "result of $num1 $operation $num2 = $result";

Upvotes: 0

Views: 348

Answers (1)

Pradeep
Pradeep

Reputation: 3153

Use eq instead of == for string comparison.

print "Please Enter Your First Number\n";
$num1 = <>;
chomp $num1;

print "Please Enter Your Operation\n";
$operation = <>;
chomp $operation;

print "Please Enter Your Second Number\n";
$num2 = <>;
chomp $num2;

if ( $operation eq "+" ) {
    $result = $num1 + $num2;
}
elsif ( $operation eq "-" ) {
    $result = $num1 - $num2;
}
elsif ( $operation eq "*" ) {
    $result = $num1 * $num2;
}
elsif ( $operation eq "/" ) {
    if ( $num2 == 0 ) {
        print "Cant Divide be Zero Mate\n";
    }
    else {
        $result = $num1 / $num2;
    }
}

print "\n";
print "result of $num1 $operation $num2 = $result";

Output:

Please Enter Your First Number
6
Please Enter Your Operation
/
Please Enter Your Second Number
3

result of 6 / 3 = 2

Upvotes: 8

Related Questions