gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 04:23:19 26 4
gpt4 key购买 nike

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

我试过了:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com