为什么使用自动化文件句柄的三参数公开调用是Perl的最佳实践? [英] Why is three-argument open calls with autovivified filehandles a Perl best practice?
问题描述
打开
函数的问题: 打开
的三参数版本比两个参数版本更好,例如 open(OUT,'>>',$ file);
vs。
open(OUT,>> $ file);
这是为什么?我曾试图告诉某人使用三参数版本,但似乎无法支持任何事情。
2)我似乎也记得autovivified文件句柄被优先于裸字文件句柄(他们称之为不同的东西)?也不记得为什么,例如
open(my $ out,'>>',$ file);
vs。
open(OUT,'>>',$ file);
它是严格
的东西吗?我似乎记得可以使用 OUT
与 strict
,但我不记得。
OUT
)不是一个好主意,因为它们在你的整个程序中是全局的 - 你需要确保没有其他例程包括模块中的那些例程使用相同的名字(包括将来)。 my $ f;打开$ f,> $ some_filename;
暴露在 $ some_filename
包含前导>
使用三参数形式避免了这一点,方法是将模式和文件名分开的参数,他们不能干涉。
此外,使用管道参数形式是一个非常好的主意:
打开$ pipe,'| - ','sendmail','fred@somewhere.fake';
比单个字符串更好 - 它避免了可能的shell注入等。 >
I've got two questions about the Perl open
function:
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);
vs.
open(OUT, ">>$file");
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) 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);
vs.
open(OUT, '>>', $file);
Is it a strict
thing? I seem to remember being able to use OUT
with strict
but I can't remember.
- 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';
Is better than doing it all as a single string – it avoids possible shell injection etc.
这篇关于为什么使用自动化文件句柄的三参数公开调用是Perl的最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!