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

时间:2013-01-30 00:06:26

标签: 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);

但这没效果。

知道怎么做到这一点吗?

由于

1 个答案:

答案 0 :(得分:10)

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

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

然后......好吧,没有“那么”。

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

注意:

  • 我把论点改为teeOutput更健全。
  • 我删除了指令(&)以覆盖teeOutput的原型。 teeOutput甚至没有。{/ li>

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

相关问题