我希望能够有一个打印到文件但不打开文件的函数--相反,应该将一个已经打开的文件句柄传递给它。这样,文件的打开和关闭只在调用代码块中发生一次。
我试过了:
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);
但这并不管用。
你知道怎么做到这一点吗?
谢谢
发布于 2013-01-30 00:11:11
首先,停止使用全局变量作为文件句柄。
open(my $RPTHANDLE, ">", $rptFilePath)
or die("Could not open file $rptFilePath: $!\n");
然后..。好吧,这里没有“然后”。
teeOutput($RPTHANDLE, 'blahblah');
teeOutput($RPTHANDLE, 'xyz');
close($RPTHANDLE);
备注:
teeOutput
的参数改为更合理的参数。&
)以覆盖teeOutput
的原型。teeOutput
甚至没有该指令。(但如果您必须处理globs,请使用teeOutput(\*STDERR, ...);
。)
https://stackoverflow.com/questions/14594451
复制相似问题