Best way to avoid “isn't numeric in numeric eq (==)”-warning

a 夏天 提交于 2019-12-12 08:48:03

问题


#!/usr/bin/env perl
use warnings;
use 5.12.2;

my $c = 'f'; # could be a number too

if ( $c eq 'd' || $c == 9 ) {
    say "Hello, world!";
} 

What is the best way, to avoid the 'Argument "f" isn't numeric in numeric eq (==) at ./perl.pl line 7.'-warning?
I suppose in this case I could use "eq" two times, but that doesn't look good.


回答1:


Not sure why you want to avoid the warning. The warning is telling you that there's a potential problem in your program.

If you're going to compare a number with a string that contains unknown data, then you're either going to have to use 'eq' for the comparison or clean up the data in some way so that you know it looks like a number.




回答2:


use Scalar::Util 'looks_like_number';    

if ( $c eq 'd' || ( looks_like_number($c) && $c == 9 ) ) {
    say "Hello, world!";
} 

You could also disable this category of warnings temporarily:

{
    no warnings 'numeric';
    # your code
}



回答3:


The obvious way to avoid a warning about comparing a non-numeric to a numeric is not to do it! Warnings are there for your benefit - they should not be ignored, or worked around.

To answer what is the best way you need to provide more context - i.e. what does $c represent, and why is it necessary to compare it do 'd' or 9 (and why not use $c eq '9')?




回答4:


Using a regular expression to see if that is a number:

if(($num=~/\d/) && ($num >= 0) && ($num < 10))
{
    # to do thing number 
}


来源:https://stackoverflow.com/questions/4131701/best-way-to-avoid-isnt-numeric-in-numeric-eq-warning

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!