我想将对文件句柄的引用传递给子例程,这样子程序中的代码可以从文件中读取并且文件句柄中的位置在调用环境中发生变化,就像在 C 中使用指针一样.
这种东西:
open my $fh, '<', $somefile or die;
dosomething(\$fh);
sub dosomething
{
my $fh_ref = shift;
while (my $l = <$$fh_ref>)
{
print $l;
print "\n";
}
}
这给出了这个输出而不是写每一行:
GLOB(0x20b8b38)
很明显我取消引用文件句柄引用错误。
附录:
while (my $l = readline($$fh_ref))
{
等等
似乎可以解决问题。我仍然想知道为什么第一种方法不起作用。
钻石运营商<...>
在 Perl 中有两种含义 -- 一种对应于 readline(HANDLE)
功能和另一个对应于glob(EXPR)
. How does perl decide which function to use?
If what's within the angle brackets is neither a filehandle nor a
simple scalar variable containing a filehandle name, typeglob, or
typeglob reference, it is interpreted as a filename pattern to be
globbed, and either a list of filenames or the next filename in the
list is returned, depending on context. This distinction is determined
on syntactic grounds alone. That means <$x>
is always a readline()
from an indirect handle, but <$hash{key}>
is always a glob()
. That's
because $x
is a simple scalar variable, but $hash{key}
is not--it's a
hash element. Even <$x >
(note the extra space) is treated as
glob("$x ")
, not readline($x)
.
解决方法是使用显式 readline
打电话
while (my $l = readline($$fh_ref)) ...
或者在括号内使用更简单的表达式。
my $fh42 = $$fh_ref;
while (my $l = <$fh42>) ...