How to make a condition with operators "+", "-", "*","/"

Asked

Viewed 56 times

2

I have the following code:

print ("Primeiro Valor: ");
$valor1 = <STDIN>;
print ("Segundo Valor: ");
$valor2 = <STDIN>;
print ("Operador: ");
$op = <STDIN>;
if ($op == "+")
{
    $total = $valor1 + $valor2;
    print ($total);
}

elsif ($op == "-")
{
    $total = $valor1 - $valor2;
    print ($total);
}

elsif ($op== "*")
{
    $total = $valor1 * $valor2;
    print ($total);
}

elsif ($op == "/")
{
    $total = $valor1 / $valor2;
    print ($total);
}

He reads everything correctly but when he enters the if if the user enters "-", "/" or "*" he always enters the first condition and makes a sum and wanted to try to understand why.

1 answer

1


In Perl, strings should be compared with the operator eq:

if ($op eq "+")
{
    $total = $valor1 + $valor2;
    print ($total);
}
elsif ($op eq "-")
{
    $total = $valor1 - $valor2;
    print ($total);
}
elsif ($op eq "*")
{
    $total = $valor1 * $valor2;
    print ($total);
}
elsif ($op eq "/")
{
    $total = $valor1 / $valor2;
    print ($total);
}

You should also call chomp to remove the line break (entered when you type the ENTER), right after reading the data:

$op = <STDIN>;
chomp($op);

if ($op eq "+") etc...

When you use ==, a numerical comparison is made. And the strings "+", "-", "*" and "/", when converted to number, result in zero. That’s why the first if will always be true, as both strings become the numeric value zero.

  • 1

    I understood now what I had done wrong, your explanation helped a lot to understand. My previous programming experience was C# and Python and I have now started Perl with some exercises and I wasn’t really able to solve this, but I understood what was wrong.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.