是否可以将文件句柄作为参数发送到PERL中的子例程?
如果是的话,您能帮忙编写一个示例代码片段,演示如何接收它并在子程序中使用它吗?
发布于 2012-12-04 04:06:45
您应该使用词法变量(open(my $fh, ...)
),对吗?如果是这样的话,你没必要做什么特别的事情。
sub f { my ($fh) = @_; print $fh "Hello, World!\n"; }
f($fh);
如果使用glob (open(FH, ...)
),只需传递对glob的引用即可。
f(\*STDOUT);
虽然许多地方也会接受地球本身。
f(*STDOUT);
发布于 2012-12-04 04:15:38
是的,您可以使用.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-04 03:53:43
是的,像这样:
some_func($fh, "hello");
其中some_func
的定义如下:
sub some_func {
my ($fh, $str) = @_;
print { $fh } "The message is: $str\n";
}
https://stackoverflow.com/questions/13702278
复制相似问题