【问题标题】:Perl assignment with a dummy placeholder带有虚拟占位符的 Perl 赋值
【发布时间】:2011-08-20 11:59:47
【问题描述】:

在我使用过的其他语言(如 Erlang 和 Python)中,如果我正在拆分字符串并且不关心其中一个字段,我可以使用下划线占位符。我在 Perl 中试过这个:

   (_,$id) = split('=',$fields[1]);

但我收到以下错误:

无法修改 ./generate_datasets.pl 第 17 行“);”附近的列表赋值中的常量项
./generate_datasets.pl 的执行由于编译错误而中止。

Perl 是否有类似的模式可以用来代替创建无用的临时变量?

【问题讨论】:

    标签: perl split


    【解决方案1】:

    undef 在 Perl 中的作用相同。

    (undef, $something, $otherthing) = split(' ', $str);
    

    【讨论】:

    • 注意:即使在声明中有效my (undef, $a, $b) = ...
    【解决方案2】:

    如果你使用Slices,你甚至不需要占位符:

    use warnings;
    use strict;
    
    my ($id) = (split /=/, 'foo=id123')[1];
    print "$id\n";
    
    __END__
    
    id123
    

    【讨论】:

      【解决方案3】:

      您可以分配给(undef)

      (undef, my $id) = split(/=/, $fields[1]);
      

      你甚至可以使用my (undef)

      my (undef, $id) = split(/=/, $fields[1]);
      

      您也可以使用列表切片。

      my $id = ( split(/=/, $fields[1]) )[1];
      

      【讨论】:

        【解决方案4】:

        只是为了解释为什么您会收到您看到的特定错误...

        _ 是一个内部 Perl 变量,可以在 stat 命令中使用,以指示“与我们在之前的 stat 调用中使用的文件相同”。这样,Perl 使用缓存的 stat 数据结构,并且不会进行另一个 stat 调用。

        if (-x $file and -r _) { ... }
        

        此文件句柄是一个常量值,无法写入。该变量存储在与$_@_ 相同的类型团中。

        perldoc stat

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2010-10-14
          • 2021-08-08
          • 2018-06-21
          • 1970-01-01
          • 2015-06-22
          • 2014-12-25
          • 1970-01-01
          相关资源
          最近更新 更多