Reputation:
I have the following piece of code in my program:
$val = chr(someFunction());
if($val == " ")
{
#do something
}
elsif($val == 0)
{
#do something else
}
But whenever 0 is passed to $val, the if part executes instead of the elsif which I expect to get executed.
How can I fix this?
Thank You.
Upvotes: 6
Views: 521
Reputation: 27183
If you had warnings enabled, you would have known what the problem was.
Run this:
use strict;
use warnings;
my $val = chr(someFunction());
if($val == " ")
{
#do something
}
elsif($val == 0)
{
#do something else
}
sub someFunction {
return 1;
}
And you get: C:>test.pl Argument " " isn't numeric in numeric eq (==) at C:\test.pl line 6. Argument "^A" isn't numeric in numeric eq (==) at C:\test.pl line 6.
Adding use diagnostics gives us this additional explanation:
(W numeric) The indicated string was fed as an argument to an operator
that expected a numeric value instead. If you're fortunate the message
will identify which operator was so unfortunate.
So, since we don't want numeric eq, we want string eq: eq
. If you didn't know that already, you could look in perldoc perlop
to read about Equality Operators.
This is a classic example of how using the warnings
and strict
pragmas saves time.
Upvotes: 3
Reputation: 64929
There are several ways to fix this (TIMTOWDI). You could import the looks_like_a_number
function from the standard Scalar::Util
package:
if (looks_like_a_number($val) and $val == 0) {
#do something
}
You could use the string equality operator
if ($val eq 0) {
#do something
}
If you have Perl 5.10, you could use the smart match operator
if ($val ~~ 0) {
#do something
}
And many more. Which method you use depends heavily on what you are trying to achieve.
Upvotes: 5
Reputation: 135295
The ==
operator is used to compare numeric values. If you want to compare strings, you should use the eq
operator.
if ($val eq " ") ...
Upvotes: 23