为什么使用自动激活文件句柄的三参数打开调用是 Perl 最佳实践? [英] Why is three-argument open calls with autovivified filehandles a Perl best practice?

查看:14
本文介绍了为什么使用自动激活文件句柄的三参数打开调用是 Perl 最佳实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个关于 Perl open 函数的问题:

I've got two questions about the Perl open function:

1) 我似乎从 Perl Best Practices 中记得 open 的 3 参数版本比两个参数版本更好,例如

1) I seem to remember from Perl Best Practices that the 3-argument version of open is better than the two argument version, e.g.

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

对比

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

这是为什么?前几天我试图告诉某人使用 3 参数版本,但似乎无法支持它.

Why is that? I was trying to tell somebody to use the 3-argument version the other day but couldn't seem to back it up with anything.

2) 我似乎还记得自动激活的文件句柄比裸字文件句柄更受青睐(他们称之为不同的东西)?也不记得为什么,例如

2) I also seem to remember autovivified filehandles being favored over bareword filehandles (they called something different)? And also couldn't remember why, e.g.

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

对比

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

这是strict 的事情吗?我似乎记得能够将 OUTstrict 一起使用,但我不记得了.

Is it a strict thing? I seem to remember being able to use OUT with strict but I can't remember.

推荐答案

  • 对文件句柄使用 typeglobs(如 OUT)不是一个好主意,因为它们在整个程序中是全局的 - 您需要确保没有其他例程包括模块中的例程使用相同的名称(包括将来).
  • 使用 open 的两个参数形式会使您的应用程序暴露于由包含特殊字符的变量引起的错误行为,例如 my $f;open $f, ">$some_filename"; 暴露于包含前导 >$some_filename 将改变程序行为的错误.莉>

    • Using typeglobs for filehandles (like OUT) is not a good idea, as they are global across your entire program - you need to be sure that no other routine including those in modules are using the same name (including in the future).
    • Using the two-argument form of open exposes your application to mis-behaviour caused by variables containing special characters, for example my $f; open $f, ">$some_filename"; is exposed to the bug where $some_filename containing a leading > will change the program's behaviour.
    • 使用三参数形式可以避免这种情况,方法是将模式和文件名分离成单独的参数,它们不会相互干扰.

      Using the three-argument form avoids this by separating the mode and filename into separate arguments where they can't interfere.

      此外,使用带有管道的多参数形式是一个非常好的主意:

      Moreover, using the lots-of-arguments form with pipes is a very good idea:

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

      比把所有事情都作为一个字符串来做要好——它避免了可能的 shell 注入等.

      Is better than doing it all as a single string – it avoids possible shell injection etc.

      这篇关于为什么使用自动激活文件句柄的三参数打开调用是 Perl 最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆