gpt4 book ai didi

perl - 如何向 Perl 子例程传递和读取文件句柄?

转载 作者:行者123 更新时间:2023-12-02 13:25:10 24 4
gpt4 key购买 nike

我想要一个从特殊文件句柄 <STDIN> 读取的 Perl 模块,并将其传递给子例程。当你看到我的代码时你就会明白我的意思。这是以前的样子:

#!/usr/bin/perl
use strict; use warnings;

use lib '/usr/local/custom_pm'
package Read_FH

sub read_file {
my ($filein) = @_;
open FILEIN, $filein or die "could not open $filein for read\n";
# reads each line of the file text one by one
while(<FILEIN>){
# do something
}
close FILEIN;

现在,子例程采用文件名(存储在 $filein 中)作为参数,使用文件句柄打开文件,并使用精细句柄逐行读取文件的每一行。

相反,我想从 <STDIN> 获取文件名,将其存储在变量中,然后将该变量作为参数传递到子例程中。从主程序:

$file = <STDIN>;
$variable = read_file($file);

该模块的子例程如下:

#!/usr/bin/perl
use strict; use warnings;

use lib '/usr/local/custom_pm'
package Read_FH

# subroutine that parses the file
sub read_file {
my ($file)= @_;
# !!! Should I open $file here with a file handle? !!!!

# read each line of the file
while($file){
# do something
}

有人知道我该怎么做吗?我很感激任何建议。

最佳答案

一般来说,使用词法文件处理程序是一个好主意。这是一个包含文件处理程序而不是裸字的词法变量。

您可以像任何其他变量一样传递它。如果您使用 File::Slurp 中的 read_file您不需要单独的文件处理程序,它将内容放入变量中。

由于尽快关闭打开的文件句柄也是一种很好的做法,如果您确实只需要获取完整的文件内容,那么这应该是首选方法。

使用文件::Slurp:

use strict;
use warnings;
use autodie;
use File::Slurp;

sub my_slurp {
my ($fname) = @_;
my $content = read_file($fname);

print $content; # or do something else with $content

return 1;
}

my $filename = <STDIN>;
my_slurp($filename);

exit 0;

没有额外的模块:

use strict;
use warnings;
use autodie;

sub my_handle {
my ($handle) = @_;
my $content = '';

## slurp mode
{
local $/;
$content = <$handle>
}

## or line wise
#while (my $line = <$handle>){
# $content .= $line;
#}

print $content; # or do something else with $content

return 1;
}

my $filename = <STDIN>;
open my $fh, '<', $filename;
my_handle($fh); # pass the handle around
close $fh;

exit 0;

关于perl - 如何向 Perl 子例程传递和读取文件句柄?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11106439/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com