Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我Getopt::Std在 Perl 脚本中使用,并且想传入零作为值。我正在检查是否使用unless(). 目前unless()正在拒绝该值未设置。
Getopt::Std
unless()
有没有办法unless()接受零作为有效值(任何非负整数都是有效的)。
这可能非常简单,但几天前我从未接触过 Perl!
富有的
您需要使用unless defined <SOMETHING> 而不是unless <SOMETHING>,因为在 Perl 中零是假的。
unless defined <SOMETHING>
unless <SOMETHING>
Perl 5 有几个错误值:0, "0", "", undef, ().
0
"0"
""
undef
()
重要的是要注意,有些事情看起来应该是假的,但事实并非如此。例如0.0是假的,因为它是等价于 的数字0,但"0.0"不是(唯一为假的字符串是空字符串 ( "") 和"0")。
0.0
"0.0"
它也有定义的概念。分配了一个值(除了 undef)的变量被称为已定义,并且在使用defined函数测试时将返回 true。
defined
鉴于您希望参数是非负整数,最好测试一下:
unless (defined $value and $value =~ /^[0-9]+$/) { #blah }