开发者

help with perl script converting use of argv to using getopts

开发者 https://www.devze.com 2023-03-28 14:49 出处:网络
I am trying to convert the use of @ARGV with using Getopt::Std instead in my perl script. I am getting some substr errors and need some help figuring this out.

I am trying to convert the use of @ARGV with using Getopt::Std instead in my perl script. I am getting some substr errors and need some help figuring this out.

Errors:

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 'und开发者_C百科ef', 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

Here is my code. (commented out code was working code using @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);
}


Even if you think Getopt::Std will do what you want, use Getopt::Long. For pretty much the same reasons you'd not just hand-roll an @ARGV handler.

To quote (in part) tchrist in http://www.nntp.perl.org/group/perl.perl5.porters/2008/05/msg136952.html:

I really like Getopt::Long...I cannot say enough good things about it to do it the justice it deserves... The only problem is that I just don't use it enough. I bet I'm not alone. What seems to happen is that at first we just want to add--oh say for example JUST ONE, SINGLE LITTLE -v flag. Well, that's so easy enough to hand-hack, that of course we do so... But just like any other piece of software, these things all seem to have a way of overgrowing their original expectations... Getopt::Long is just wonderful, up--I believe--to any job you can come up with for it. Too often its absence means that I've in the long run made more work for myself--or others--by not having used it originally.


"getopt, getopts - Process single-character switches with switch clustering"

As only single character switches are allowed $opt{fd} and $opt{ld} are undef.

Getopt::Long does what you want.

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

精彩评论

暂无评论...
验证码 换一张
取 消