我希望能够有一个打印到文件但不打开文件的函数 - 而应该传递已经打开的文件句柄.这样,文件打开和关闭仅在调用代码块中发生一次.
我试过了:
sub teeOutput
{
my $str = $_[0];
my $hndl = $_[1];
#print to file
print $hndl $str;
#print to STDOUT
print $str;
}
Run Code Online (Sandbox Code Playgroud)
然后在调用时
open(RPTHANDLE, ">", $rptFilePath) || die("Could not open file ".$rptFilePath);
&teeOutput('blahblah', RPTHANDLE);
&teeOutput('xyz', RPTHANDLE);
close(RPTHANDLE);
Run Code Online (Sandbox Code Playgroud)
但那没用.
知道怎么做到这一点?
谢谢
ike*_*ami 10
首先,停止对文件句柄使用全局变量.
open(my $RPTHANDLE, ">", $rptFilePath)
or die("Could not open file $rptFilePath: $!\n");
Run Code Online (Sandbox Code Playgroud)
然后......好吧,没有"那么".
teeOutput($RPTHANDLE, 'blahblah');
teeOutput($RPTHANDLE, 'xyz');
close($RPTHANDLE);
Run Code Online (Sandbox Code Playgroud)
笔记:
teeOutput更健全.&)以覆盖teeOutput原型.teeOutput甚至都没有.(但如果你必须处理globs,请使用teeOutput(\*STDERR, ...);.)