问题描述
有人说我们应该使用词法文件句柄而不是 typeglob,像这样:
Some say we should use a lexical filehandle instead of a typeglob, like this:
open $fh, $filename;
但大多数 Perl 书籍,包括美洲驼书,使用 typeglob,像这样:
But most Perl books, including The Llama Book, use a typeglob, like this:
open LOGFILE, $filename;
那么有什么区别呢?哪个被认为是更好的做法?
So what are the differences? Which one is considered a better practice?
推荐答案
词法文件句柄可以很容易地作为参数传递,文件句柄不能.Typeglobs 可以(或至少对它们的引用可以),但这有点混乱.考虑坚持使用词法变量,并确保首先声明它们,以便您知道它们是真正的词法变量而不是局部或全局变量.即
Lexical filehandles can be passed easily as arguments, filehandles cannot. Typeglobs can (or at least references to them can), but that's kinda messy. Consider sticking with lexical variables, and make sure to declare them first, so you know that they're really lexical and not local or global. I.e.
my $fh;
open $fh, $filename;
还可以考虑使用 IO::Handle
或 IO::File
作为选项.曾经是 FileHandle
,但被 ysth 通知低于 FileHandle
现在只是依次使用 'IO::Handle',这对我来说是 5.6 以来的新闻,但这里有很多东西要学.:-)
Also consider using IO::Handle
or IO::File
as options. Used to be FileHandle
but was informed by ysth below that FileHandle
now just uses 'IO::Handle' in turn, which is news to me since 5.6, but there's a lot to learn here. :-)
另外,不要忘记use strict
:-)
Also, don't forget use strict
:-)
这篇关于哪个是好的实践,是词法文件句柄还是 typeglob?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!