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

标签 perl

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

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/

相关文章:

linux - Perl 在文件中搜索和替换错误 "Bareword found where operator expected"

c++ - Perl - 2 的补码模 256 - C++ 等价物

mysql - Perl:如何将远程 MYSQL 表复制/镜像到另一个数据库?可能结构也不同?

perl - 在Perl中使用sockaddr_in()导致此使用错误的原因是什么?

perl - 用于修复 .txt 文件中断行的脚本?

perl - 警告 : something's wrong when ref $body->param->{aa}

perl - 如何在 perl 中使用给定的 'OR'?

perl - 调试调用 DynaLoader 库的 AUTOLOAD

eclipse - Eclipse 的 EPIC(Perl 插件)仍在积极开发中吗?

perl - 我什么时候应该使用 `use` ?