我正在嘗試創建幾個可以一起工作的函數。 getFH
應採用打開文件的模式(>
或<
),然後是文件本身(從命令行)。它應該做一些檢查,看看文件是否可以打開,然後打開它,並返回文件句柄。 doSomething
應該接受文件句柄,並循環數據並執行任何操作。但是,當程序行到while循環,我得到的錯誤:從子程序返回文件句柄並傳遞給其他子例程
readline() on unopened filehandle 1
我在做什麼錯在這裏?
#! /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 $_;
}
}
啊,我知道這是一些簡單的類似。感謝@Dave Sherohman,再次讓Perl感到舒服。在R編程全年夏天 –