1

我正在尝试Getopt::Std在我的 perl 脚本中使用 using 来转换 @ARGV 的使用。我收到了一些 substr 错误,需要一些帮助来解决这个问题。

错误:

Use of uninitialized value in substr at ./h.pl line 33.
Use of uninitialized value in substr at ./h.pl line 33.
substr outside of string at ./h.pl line 33.
Use of uninitialized value in substr at ./h.pl line 33.
substr outside of string at ./h.pl line 33.
The 'month' parameter (undef) to DateTime::new was an 'undef', which is not one of the allowed types: scalar
 at /usr/lib64/perl5/vendor_perl/5.8.8/x86_64-linux-thread-multi/DateTime.pm line 176
    DateTime::new('undef', 'HASH(0xb6932d0)') called at ./h.pl line 33

这是我的代码。(注释掉的代码是使用@ARGV 的工作代码)

use strict;
use warnings;
use Getopt::Std;
use DateTime;

# Getopt usage
my %opt;
getopts ('fd:ld:h', \%opt);

$opt{h} and &Usage;
my $first_date     = $opt{fd};
my $last_date      = $opt{ld};

#unless(@ARGV==2)
#{
#    print "Usage: myperlscript first_date last_date\n";
#    exit(1);
#}
#
#my ($first_date,$last_date)=@ARGV;

# Convert using Getopts
my $date=DateTime->new(
{
  year=>substr($first_date,0,4),
  month=>substr($first_date,4,2),
  day=>substr($first_date,6,2)
});

while($date->ymd('') le $last_date)
{
  print $date->ymd('') . "\n";
  $date->add(days=>1);
}
4

2 回答 2

3

即使您认为 Getopt::Std 会做您想做的事,也请使用 Getopt::Long。出于几乎相同的原因,您不只是手动滚动@ARGV 处理程序。

http://www.nntp.perl.org/group/perl.perl5.porters/2008/05/msg136952.html中引用(部分)tchrist :

真的很喜欢 Getopt::Long...我不能说足够多的关于它的好话来做它应得的正义...唯一的问题是我没有足够地使用它。我敢打赌我并不孤单。似乎发生的情况是,起初我们只想添加——哦,比如说 JUST ONE, SINGLE LITTLE -v 标志。好吧,这很容易手动破解,我们当然会这样做......但就像任何其他软件一样,这些东西似乎都有一种过度增长他们最初期望的方式...... Getopt::Long 是太棒了,我相信你能想到的任何工作。很多时候,它的缺席意味着从长远来看,我为自己或其他人做了更多的工作,因为最初没有使用它。

于 2011-08-14T21:54:17.287 回答
2

“getopt、getopts - 使用交换机集群处理单字符交换机”

因为只允许单字符开关$opt{fd}并且$opt{ld}是 undef。

Getopt::Long做你想做的事。

use strict;
use warnings;
use Getopt::Long;

my $fd;
my $ld;

my $result = GetOptions(
    'fd=s' => \$fd,
    'ld=s' => \$ld,
);

die unless $result;

print "fd: $fd\n";
print "ld: $ld\n";
于 2011-08-14T21:21:07.240 回答