aminards
aminards

Reputation: 421

How can I avoid warnings when checking element in array for numeric equivalency to zero even though some elements are character strings?

I would like to not get the warning that the value being checked isn't numeric in numeric eq (==) when checking for the number zero in an array of arrays that includes character string elements and numeric elements.

I am working with an array of arrays (aoa) in Perl. Some elements in the aoa are character strings and some are numeric. I need to check if the element $aoa[$i][$j] is the number zero. I am using this code.

if($aoa[$i][$j] == '0'){
    next;
}

This produces tons of warnings (one for each check on a character element - my data has several hundred thousand elements to check) that the "argument isn't numeric in numeric eq (==)".
I want to not see these warnings. Other than specifically suppress this warning at this point in my code, can I do my check any differently such that it will not produce these warnings at this step?

This isn't so much to make my code work better for my task, it is simply to stop getting a ton of warnings that make you think something isn't working correctly in the code. When you tell someone, "oh, don't worry about all those warnings - it is working fine" some people tend to not believe you!

Upvotes: 3

Views: 139

Answers (2)

Dave Cross
Dave Cross

Reputation: 69244

You could use looks_like_number() (from Scalar::Util):

use Scalar::Util 'looks_like_number';

if (looks_like_number($aoa[$i][$j]) and $aoa[$i][$j] == '0'){
    next;
}

Or something like this:

# If the value has a length and is false, then it
# must be 0 or 0.0.
if (length($aoa[$i][$j]) and ! $aoa[$i][$j]) {
    next;
}

Upvotes: 6

TFBW
TFBW

Reputation: 1019

As always, there are several ways to do it. If none of your elements are undef, then you can test for falseness and ne '', as in if (!$x && $x ne '') {} (using $x for brevity). That won't catch certain expressions of zero, such as "0E0" or "0 but true". If those matter to you, then another approach is to use the looks_like_number() function from the standard Scalar::Util module. That way you can say if (looks_like_number($x) && $x == 0) {} without fear of warnings. You could also simply say if ($x eq '0') {} if you're sure that your zeros are in normal form, because it's valid to do a string comparison against a number (but not vice versa).

Good for you wanting to eliminate warnings, by the way.

Upvotes: 3

Related Questions