从子例程中的文件句柄引用中读取

Reading from a filehandle reference in a subroutune

我想将对文件句柄的引用传递给子例程,这样子程序中的代码就可以从文件中读取并且文件句柄中的位置在调用环境中发生变化,就像使用指针一样在 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>) ...