【发布时间】:2012-06-19 17:44:44
【问题描述】:
我想要一个从特殊文件句柄<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
}
有人知道我该怎么做吗?我很感激任何建议。
【问题讨论】:
-
我理解正确,您是否需要一个 CPAN 模块,或者您需要帮助更改您的模块以从
<STDIN>获取文件名? -
我需要帮助更改我的模块以从
<STDIN>获取文件名 -
你有没有试过把这两行代码放到你的模块中?
-
我做了,但我不知道如何测试它以查看它是否有效,甚至不知道如何编译它以查看其语法是否正确。
-
请使用open的三参数形式。使用两个参数的形式,如果 '
' + chomp() 给你留下像 rm -rf / |这样的文件名,你可能会不高兴。
标签: perl subroutine filehandle