gpt4 book ai didi

perl - 在 Perl 中,如何检查未定义的 OR 空白参数?

转载 作者:行者123 更新时间:2023-12-03 22:47:20 25 4
gpt4 key购买 nike

我有一些像下面这样的代码:

if (not defined $id) {
print "Enter ID number: ";
chomp ($id = <STDIN>);
exit 0 if ($id eq ""); # If empty string, exit.
}
if (not defined $name) {
print "Enter name: ";
chomp ($name = <STDIN>);
exit 0 if ($name eq ""); # If empty string, exit.
}
if (not defined $class) {
print "Enter class: ";
chomp ($class = <STDIN>);
exit 0 if ($class eq ""); # If empty string, exit.
}
我希望能够只传递其中的一些(例如,名称和类,但不传递 ID),为未传递的传递空白,所以我认为以下方法可行:
if (not defined $id || $id eq "") {
print "Enter ID number: ";
chomp ($id = <STDIN>);
exit 0 if ($id eq ""); # If empty string, exit.
}
但是如果我通过了,它似乎不起作用,例如,以下内容:
perl "myperlroutine.pl" "" "Mickey Mouse" "Entry"
命令窗口(我在 Windows 上运行它)短暂出现然后立即消失。
我错过了一些明显的东西吗?

最佳答案

您正在使用低优先级 not您应该在哪里使用高优先级 ! .
所以你说:

if ( not( defined $id || $id eq "" ) )
就像:
if ( ! defined $id && $id ne '' )
这总是错误的。
也一样
if ( ! defined $id || $id eq '' )
反而。
在 Perl 5.12 及更高版本中,length() 在传递 undef 时不再发出警告,这非常方便。所以你可以简单地做:
if ( ! length $id ) {
这是短代码,但如果 $id 可能效率低下可能是一个很长的 UTF-8 字符串,很难确定长度。在那里我更倾向于这样做:
if ( ( $id // '' ) eq '' ) {
但是除非您熟悉该习语,否则这不是 super 可读的。

关于perl - 在 Perl 中,如何检查未定义的 OR 空白参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25651126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com