代码之家  ›  专栏  ›  技术社区  ›  Morinar

为什么使用Autovified filehandles的三参数开放调用是Perl的最佳实践?

  •  45
  • Morinar  · 技术社区  · 16 年前

    我有两个关于Perl的问题 open 功能:

    1) 我好像还记得从哪里来的 3参数版本的

    open(OUT, '>>', $file);
    

    vs。

    open(OUT, ">>$file");
    

    为什么呢?前几天我试图告诉某人使用3参数版本,但似乎没有任何支持。

    open(my $out, '>>', $file);
    

    vs。

    打开(OUT,“>”,$file);
    

    这是一辆汽车吗 strict OUT 具有 但我不记得了。

    3 回复  |  直到 10 年前
        1
  •  64
  •   daxim Fayland Lam    16 年前
    • 将typeglobs用于文件句柄(如 OUT
    • 例如,使用open的双参数形式会使应用程序暴露于由包含特殊字符的变量引起的错误行为 my $f; open $f, ">$some_filename"; 暴露于错误的地方 $some_filename > 将改变程序的行为。

    此外,将大量参数表单与管道一起使用是一个非常好的主意:

    open $pipe, '|-', 'sendmail', 'fred@somewhere.fake';
    

    这比把它全部作为一根绳子来做要好,它避免了可能的外壳注入等。

        2
  •  16
  •   Paul Nathan    16 年前

    处理#2:

    OUT 是一个全局文件句柄,使用它会使您暴露于如下隐藏的错误:

    sub doSomething {
      my ($input) = @_;
      # let's compare $input to something we read from another file
      open(F, "<", $anotherFile);
      @F = <F>; 
      close F;
      &do_some_comparison($input, @F);
    }
    
    open(F, "<", $myfile);
    while (<F>) {
        &doSomething($_);   # do'h -- just closed the F filehandle
    }
    close F;
    
        3
  •  13
  •   dland    16 年前

    需要记住的一个方面是,两个arg形式被破坏了。考虑一个名为“ABC”的文件(即,一个文件名为一个超前空白)。无法打开该文件:

    open my $foo, ' abc' or die $!;
    open my $foo, '< abc' or die $!;
    open my $foo, '<  abc' or die $!;
    # nothing works
    

    空间被删除,因此无法再找到该文件。这种情况极不可能发生,但肯定是个问题。三个arg表单对此免疫:

    open my $foo, '<', ' abc' or die $!;
    # works
    

    This thread 刚出现的