我如何告诉 Perl 函数从特殊的 ARGV 句柄中读取文件?
在 perldoc perlvar
中,我读到了以下内容:
请注意,目前“ARGV”仅具有 其神奇功效在“<>”中 操作员;在其他地方它只是一个简单的 最后一个对应的文件句柄 由“<>”打开的文件。尤其, 将“*ARGV”作为参数传递给 需要文件句柄的函数可能 不会导致你的功能 自动读取全部内容 @ARGV 中的文件。
那么,我如何将 *ARGV
(或类似的东西)作为参数传递给需要文件句柄的函数,并让该函数读取 < 中的所有文件代码>@ARGV?
In perldoc perlvar
, I read this:
Note that currently "ARGV" only has
its magical effect within the "<>"
operator; elsewhere it is just a plain
filehandle corresponding to the last
file opened by "<>". In particular,
passing "*ARGV" as a parameter to a
function that expects a filehandle may
not cause your function to
automatically read the contents of all
the files in @ARGV.
So, how can I pass *ARGV
(or something that resembles it) as a paramter to a function that expects a filehandle, and have that function read all the files in @ARGV
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
继续并传入
*ARGV
类型 glob 或\*ARGV
及其引用。只需确保最终使用它的函数是通过<$fh>
运算符或readline($fh)
(其底层功能等效项)来实现的。perlvar 联机帮助页中引用的段落中解决的问题只是想提醒您,如果您有任何操作,您将无法触发
ARGV
的 magic open在句柄上使用除readline
之外的其他读取机制,例如read
、sysread
或getc
。运行它来向自己证明它是有效的:
将其放入文件中,然后使用多个文件参数运行它:
看到了吗?效果很好。
Go right ahead and pass in the
*ARGV
typeglob or\*ARGV
, its reference. Just make sure that the function eventually making use of it does so via the<$fh>
operator orreadline($fh)
, its underlying functional equivalent.The issue addressed in the cited passage from the perlvar manpage is just trying to remind you that you won't be able to get
ARGV
’s magic open to trigger if you any use other reading mechanism thanreadline
on the handle, such asread
,sysread
, orgetc
.Run this to prove to yourself it works:
Put that in a file, then run it with several file arguments:
See? It works fine.
迭代重载对象时,您可以重新分派到
<>
:ReadARGV
包包含一个简单的对象构造函数new
,然后重载>
运算符来简单地调用<>
。You can redispatch to
<>
when iterating an overloaded object:The
ReadARGV
package contains a simple object constructornew
and then overloads the<HANDLE>
operator to simply call<>
.你可以用
cat
来伪造它(在Unix系统上),这样你就失去了一些魔力(
$ARGV
,$.
)。我确信也有一种方法可以处理绑定的文件句柄(请参阅
perltie
)。You could fake it with
cat
(on a Unix system)You lose some of the magic (
$ARGV
,$.
) with this.I'm sure there's a way to do with a tied filehandle, too (see
perltie
).