我正在尝试使用Getopt :: Long模块打开输入文件作为参数
这是我的剧本的开头
#! /usr/bin/perl -s
use strict;
use warnings;
use Data::Dumper;
local $Data::Dumper::Useqq = 1;
use Getopt::Long qw(GetOptions);;
my $input='';
GetOptions('input|in=s' => \$input);
open(my $table1,'<', $input) or die "$! - [$input]"; #input file
这就是我启动脚本的方式
$ script.pl -in /path/to/file.txt
我得到了输出:
在script.pl第13行没有这样的文件或目录 - []。
第13行是open(...
的行。
脚本中有错误吗?
答案 0 :(得分:3)
你正在使用Perl的内置选项解析你的shebang行中的-s
。在像script.pl -in /path/to/file.txt
这样的命令中,perl将变量$in
设置为1,并在@ARGV
看到之前从Getopt::Long
删除相应的条目
只需从shebang行中删除-s
以及它将为您工作的所有内容
答案 1 :(得分:1)
否,脚本中没有错误。你的代码正在做你告诉它做的事情。
它正在调用该行的die "$! - [$input]";
部分,因为open
返回了 false 值。
此类文件或目录不是$!
的内容。这是它遇到的错误。在[]
之间,$input
的值为空。所以你的问题就出现了。您将空字符串传递给open
,然后失败。
你的方法是错误的。
Getopt :: Long要求长度超过一个字母的选项以--
作为前缀。这意味着-in
应为--in
。
$ script.pl --in /path/to/file.txt
因为您没有这样做,Getopt :: Long没有看到您的选项,也没有解析它。你初始化$input = ''
有点高,所以它保持空字符串。
您可以添加一项检查以确保始终提供输入文件。
use strict;
use warnings;
use Getopt::Long qw(GetOptions);;
my $input = '';
GetOptions('input|in=s' => \$input);
die 'the --input option is required!' unless $input;
open(my $table1,'<', $input) or die "$! - [$input]"; #input file