避免"数字eq(==)中不是数字"的最佳方法 - 警告

sid*_*com 7 perl warnings equality operators

#!/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!";
} 
Run Code Online (Sandbox Code Playgroud)

什么是最好的方法,避免'参数'f"在./perl.pl第7行的数字eq(==)中不是数字.' - 警告?
我想在这种情况下我可以使用"eq"两次,但这看起来不太好.

Eug*_*ash 25

use Scalar::Util 'looks_like_number';    

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

您还可以暂时禁用此类警告:

{
    no warnings 'numeric';
    # your code
}
Run Code Online (Sandbox Code Playgroud)


Dav*_*oss 17

不确定为什么要避免警告.警告告诉您程序中存在潜在问题.

如果您要将数字与包含未知数据的字符串进行比较,那么您将不得不使用"eq"进行比较或以某种方式清理数据,以便您知道它看起来像一个数字.