views:

296

answers:

3

Hello,

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.

+23  A: 

The == operator is used to compare numeric values. If you want to compare strings, you should use the eq operator.

if ($val eq " ") ...
1800 INFORMATION
Also, are you sure that you want to test whether $val is exactly one space character? If you want the first branch of your "if" statement to execute whenever $val contains one or more spaces, use a regex instead.
j_random_hacker
+5  A: 

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.

Chas. Owens
Thanks a lot for the explanation :)
+3  A: 

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.

daotoad