在perl中将文件句柄作为参数发送

Daa*_*ish 3 perl filehandle

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

如果是,您是否可以帮助显示如何接收它并在子例程中使用它的示例代码段?

ike*_*ami 9

你正在使用词法变量(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)


Vij*_*jay 5

是的,您可以使用.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)


mel*_*ene 4

是的,像这样:

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)