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

发布于 2024-09-30 23:12:18 字数 293 浏览 7 评论 0原文

#!/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!";
} 

避免出现“Argument "f" isn't numeric in numeric eq (==) at ./perl.pl line 7.”警告的最佳方法是什么?
我想在这种情况下我可以使用“eq”两次,但这看起来不太好。

#!/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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

许久 2024-10-07 23:12:19

使用正则表达式来查看它是否是一个数字:

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

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

if(($num=~/\d/) && ($num >= 0) && ($num < 10))
{
    # to do thing number 
}
笛声青案梦长安 2024-10-07 23:12:18
use Scalar::Util 'looks_like_number';    

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

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

{
    no warnings 'numeric';
    # your code
}
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
}
友欢 2024-10-07 23:12:18

不知道为什么你想避免警告。该警告告诉您程序中存在潜在问题。

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

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.

奶茶白久 2024-10-07 23:12:18

避免出现有关将非数字与数字进行比较的警告的明显方法是不这样做!警告是为了您的利益而存在的 - 它们不应被忽视或解决。

要回答什么是最佳方式,您需要提供更多上下文 - 即 $c 代表什么,以及为什么有必要比较它 'd'9 (为什么不使用 $c eq '9')?

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')?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文