2011-08-14 21 views
1

我想轉換使用@ARGV與使用Getopt::Std而不是在我的Perl腳本。 我得到一些substr錯誤,需要一些幫助搞清楚這一點。幫助perl腳本轉換使用argv使用getopts

錯誤:

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)[email protected]; 

# 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); 
} 

回答

2

-

由於只有單個字符開關被允許$opt{fd}$opt{ld}是爲undef「getopt的,getopts的工藝單字符與開關聚類切換」。

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"; 
+0

謝謝你的澄清。 – jdamae

3

即使您認爲Getopt :: Std將按照您的要求進行操作,請使用Getopt :: Long。基於幾乎相同的原因,你不會手動使用@ARGV處理程序。

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

我真的 Getopt的::長......我不能說不夠好東西它做它應有的正義?唯一的問題是我只是不夠用。我敢打賭,我並不孤單。看起來會發生的是,我們剛開始時只想添加 - 例如說只是一個,單個小-v標誌。那麼,這是非常容易的手工破解,當然我們這樣做......但就像其他任何軟件一樣,這些東西似乎都有一種超出他們原來期望的方式... Getopt :: Long是隻要精彩,我相信 - 你可以爲它做出任何工作。它的缺席常常意味着我從最初沒有使用它,爲我自己或其他人創造了更多的工作。

+0

我不久前讀過另一篇博客文章,迴應了這種非常的感悟;應該總是使用Getopt :: Long來做所有命令行選項。我正在梳理互聯網尋找鏈接,但也許別人記得? –

+0

我曾經引用perlmonks(早在2008年),很有可能在最近這裏引用。 – ysth