你正在使用词法变量(open(my $fh, ...)),对吧?如果是这样,您不必做任何特别的事情.
sub f { my ($fh) = @_; print $fh "Hello, World!\n"; }
f($fh);
Run Code Online (Sandbox Code Playgroud)
如果你正在使用glob(open(FH, ...)),只需传递一个对glob的引用.
f(\*STDOUT);
Run Code Online (Sandbox Code Playgroud)
虽然很多地方也会接受glob本身.
f(*STDOUT);
Run Code Online (Sandbox Code Playgroud)
是的,您可以使用.below作为示例代码。
#!/usr/bin/perl
use strict;
use warnings;
open (MYFILE, 'temp');
printit(\*MYFILE);
sub printit {
my $fh = shift;
while (<$fh>) {
print;
}
}
Run Code Online (Sandbox Code Playgroud)
下面是测试:
> cat temp
1
2
3
4
5
Run Code Online (Sandbox Code Playgroud)
perl脚本样本
> cat temp.pl
#!/usr/bin/perl
use strict;
use warnings;
open (MYFILE, 'temp');
printit(\*MYFILE);
sub printit {
my $fh = shift;
while (<$fh>) {
print;
}
}
Run Code Online (Sandbox Code Playgroud)
执行
> temp.pl
1
2
3
4
5
>
Run Code Online (Sandbox Code Playgroud)
是的,像这样:
some_func($fh, "hello");
Run Code Online (Sandbox Code Playgroud)
其中some_func定义如下:
sub some_func {
my ($fh, $str) = @_;
print { $fh } "The message is: $str\n";
}
Run Code Online (Sandbox Code Playgroud)