【发布时间】:2017-10-14 14:11:49
【问题描述】:
我正在尝试创建几个可以协同工作的函数。 getFH 应该采用打开文件的模式(> 或 <),然后是文件本身(从命令行)。它应该检查文件是否可以打开,然后打开它,并返回文件句柄。 doSomething 应该接受文件句柄,并循环数据并做任何事情。但是,当程序进入 while 循环时,我得到了错误:
未打开的文件句柄 1 上的 readline()
我在这里做错了什么?
#! /usr/bin/perl
use warnings;
use strict;
use feature qw(say);
use Getopt::Long;
use Pod::Usage;
# command line param(s)
my $infile = '';
my $usage = "\n\n$0 [options] \n
Options
-infile Infile
-help Show this help message
\n";
# check flags
GetOptions(
'infile=s' => \$infile,
help => sub { pod2usage($usage) },
) or pod2usage(2);
my $inFH = getFh('<', $infile);
doSomething($inFH);
## Subroutines ##
## getFH ##
## @params:
## How to open file: '<' or '>'
## File to open
sub getFh {
my ($read_or_write, $file) = @_;
my $fh;
if ( ! defined $read_or_write ) {
die "Read or Write symbol not provided", $!;
}
if ( ! defined $file ) {
die "File not provided", $!;
}
unless ( -e -f -r -w $file ) {
die "File $file not suitable to use", $!;
}
unless ( open( $fh, $read_or_write, $file ) ) {
die "Cannot open $file",$!;
}
return($fh);
}
#Take in filehandle and do something with data
sub doSomething{
my $fh = @_;
while ( <$fh> ) {
say $_;
}
}
【问题讨论】:
标签: perl filehandle