【问题标题】:Perl - Use of uninitialized value?Perl - 使用未初始化的值?
【发布时间】:2011-07-19 03:02:59
【问题描述】:

所以我正在尝试运行这段代码...

my $filePath = $ARGV['0'];
if ($filePath eq ""){
    print "Missing argument!";
}

它应该检查第一个命令行参数,并告诉我它是否为空,但它返回此错误,我不知道为什么:

Use of uninitialized value $filePath in string eq at program.pl line 19.

我做错了什么?

【问题讨论】:

  • 数组索引周围的' 是什么?

标签: perl command-line-arguments


【解决方案1】:

如果未定义,则另一种答案是设置默认值:

my $filePath = $ARGV[0] // '';

【讨论】:

    【解决方案2】:

    只需检查 $ARGV[0] 是否已定义

    #!/usr/bin/perl
    use strict;
    use warnings;
    
    if(!defined $ARGV[0]){
        print "No FilePath Specified!\n";
    }
    

    如果没有通过命令行,这将打印“No FilePath Specified!\n”。

    您遇到的问题是您将 $filePath 设置为未定义的值。警告正在抱怨,因为您随后尝试将未定义的值与“”进行比较。警告认为这是值得告诉你的。

    我使用我的示例展示了一种检查是否已定义的简洁方法,但从技术上讲,您也可以这样做:

    if(!@ARGV){
        print "No FilePath Specified!\n";
    }
    

    【讨论】:

      【解决方案3】:

      编辑:正如@Andrew 指出的那样,这不一样,因为文件名“0”会失败

      另外,代替

      if ((!defined $filePath) || ($filePath eq "")) { ...

      正如@Mat 所写。你可以使用更简单的

      if(!$filePath) { ...

      完全一样

      【讨论】:

      • 并非 100% 相同。这会将完全合法的文件名“0”视为错误。
      【解决方案4】:

      空和未初始化不是一回事。您可以使用defined 运算符检查变量是否已初始化,例如:

      if ((!defined $filePath) || ($filePath eq "")) {
       # $filePath is either not initialized, or initialized but empty
       ...
      }
      

      我很确定你是这个意思:

      my $filePath = $ARGV[0];
      

      (不带引号)

      【讨论】:

      • “||”选项不是 100% 相同的。它会将完全合法的文件名“0”视为缺失,并提供默认值。
      • 我喜欢:if ( ! defined $filePath || ! length $filePath )
      猜你喜欢
      • 1970-01-01
      • 2013-04-08
      • 1970-01-01
      • 2016-09-25
      • 2015-06-03
      • 1970-01-01
      • 2014-02-05
      • 1970-01-01
      • 2012-06-20
      相关资源
      最近更新 更多