哪一个是最佳实践,一个词法文件句柄还是一个typeglob? [英] Which one is good practice, a lexical filehandle or a typeglob?

查看:72
本文介绍了哪一个是最佳实践,一个词法文件句柄还是一个typeglob?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人说我们应该使用词汇文件句柄而不是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?

推荐答案

词汇文件句柄可以轻松地作为参​​数传递,而文件句柄则不能. Typeglob可以(或者至少是对它们的引用可以),但这有点混乱.考虑使用词法变量,并确保先声明它们,以便您知道它们确实是词法而不是局部或全局的.即

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::HandleIO::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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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