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

标签 perl reference subroutine filehandle

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

关于perl - 从子例程中的文件句柄引用中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51483705/

相关文章:

Perl 十六进制 CRC-16 位脚本

perl - 可以在 perl 中定义一个变量,其值不能在子例程中更改吗?

Perl SOAP::LITE——无法验证?

perl - 如何在perl的Expect模块中使用expect命令搜索同一字符串的多次出现

perl - 在 Perl Catalyst 应用程序的配置变量上加载模块

perl - Thrift::TException=HASH(0x25d18e0) 错误

c++ - std::vector 插入对象的拷贝或引用?

c++ - 唯一_Ptr : Attemting To Reference A Deleted Function

C++ 偏特化匹配引用类型

.net - Vb.net 两个逗号分隔的列表