4

是否可以将文件句柄作为参数发送到 PERL 中的子例程?

如果是,您能否提供一个示例代码片段来说明如何接收它并在子例程中使用它?

4

3 回答 3

12

You're using lexical variables (open(my $fh, ...)) as you should, right? If so, you don't have to do anything special.

sub f { my ($fh) = @_; print $fh "Hello, World!\n"; }
f($fh);

If you're using a glob (open(FH, ...)), just pass a reference to the glob.

f(\*STDOUT);

Though many places will also accept the glob itself.

f(*STDOUT);
于 2012-12-04T12:06:45.460 回答
5

是的,您可以使用 .below 来实现。下面是相同的示例代码。

#!/usr/bin/perl

use strict;
use warnings;

open (MYFILE, 'temp');

printit(\*MYFILE);

sub printit {
    my $fh = shift;
    while (<$fh>) {
        print;
    }
}

下面是测试:

> cat temp
1
2
3
4
5

perl 脚本示例

> cat temp.pl
#!/usr/bin/perl

use strict;
use warnings;

open (MYFILE, 'temp');
printit(\*MYFILE);
sub printit {
    my $fh = shift;
    while (<$fh>) {
        print;
    } 
}

执行

> temp.pl
1
2
3
4
5
> 
于 2012-12-04T12:15:38.533 回答
4

是的,像这样:

some_func($fh, "hello");

wheresome_func定义如下:

sub some_func {
    my ($fh, $str) = @_;
    print { $fh } "The message is: $str\n";
}
于 2012-12-04T11:53:43.360 回答