perl - 在 Perl 中将文件句柄作为函数 arg 传递

标签 perl

我希望能够拥有一个打印到文件但不打开文件的函数——而是应该将一个已经打开的文件句柄传递给它。这样文件的打开和关闭只在调用代码块中发生一次。

我试过了:

sub teeOutput
{
    my $str = $_[0];
    my $hndl = $_[1];

    #print to file
    print $hndl $str;
    #print to STDOUT
    print $str;
}

然后在调用时

open(RPTHANDLE, ">", $rptFilePath) || die("Could not open file ".$rptFilePath);

&teeOutput('blahblah', RPTHANDLE);
&teeOutput('xyz', RPTHANDLE);

close(RPTHANDLE);

但这没有用。

知道如何做到这一点吗?

谢谢

最佳答案

首先,停止对文件句柄使用全局变量。

open(my $RPTHANDLE, ">", $rptFilePath)
   or die("Could not open file $rptFilePath: $!\n");

那么……嗯,没有“那么”。

teeOutput($RPTHANDLE, 'blahblah');
teeOutput($RPTHANDLE, 'xyz');
close($RPTHANDLE);

注意事项:

  • 我将 teeOutput 的参数颠倒为更理智的东西。
  • 我删除了指令 (&) 以覆盖 teeOutput 的原型(prototype)。 teeOutput 甚至没有。

(但如果您必须处理 glob,请使用 teeOutput(\*STDERR, ...);。)

关于perl - 在 Perl 中将文件句柄作为函数 arg 传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14594451/

相关文章:

perl - 如何将 Devel::Cover 与证明一起使用?

regex - 如何使用 perl 正则表达式将制表符变成 block 引号

perl - 在 Perl 脚本中使用来自 YAML 配置文件的数据的简单示例

linux - Crontab 无法运行我的 Perl 模块

linux - 为什么 strftime 大写标志 '^' 不起作用?

arrays - 为什么 Perl 有时会回收引用?

multithreading - Perl - 多线程脚本打印内存映射和回溯

perl - 使用perl进行哈希键排序?

perl - 使用 SWIG 将二进制数据移入/移出 Perl

perl - 如何使用 shell(awk、sed 等)删除文件中的前两列