On Thu, Jun 17, 2010 at 07:50, Shawn H Corey <shawnhco...@gmail.com> wrote: > On 10-06-17 02:36 AM, Unknown User wrote: >> >> I have the following code: >> >> GetOptions( >> "n|name=s" => \$name, >> "a|age=i" => \$age, >> "s|sex=s" => \$sex, >> ) || die "Bad options\n";; > > GetOptions( > "name=s" => \$name, > "age=i" => \$age, > "sex=s" => \$sex, > ) || die "Bad options\n"; > > # GetOptions automatic determines which option by > # the minimum leading letters needed to > # distinguish them. > >> >> What i expected this code to do is to die if a bad option was given, >> say -s without an arguement, as in ./myprog -n name -s -a 20 >> However, it does not do that. >> >> What would be the correct method to die if one of the options is not >> complete? >> > > But they are complete. 'name' is placed in $name, '-a' is placed in $sex, > and @ARGV is left with ( '20' ). snip
Good point, try this: #!/usr/bin/perl use strict; use warnings; use Getopt::Long; #to test, run with no args unless (@ARGV) { for my $args ( [ qw/-n name -a 5 -s M/ ], [ qw/-n -a 5 -s M/ ], [ qw/-n name -a a -s M/ ], [ qw/-n name -a -s M/ ], [ qw/-n name -a 5 -s W/ ], [ qw/-n name/ ], ) { print "$0 @$args\n"; system $^X, $0, @$args; print "-" x 5, "\n\n"; } print "$0\n"; } GetOptions( "n|name=s" => \(my $name = "DEFAULT"), "a|age=n" => \(my $age = "DEFAULT"), "s|sex=s" => \(my $sex = "DEFAULT"), ) or die "bad options\n"; my $errfmt = qq{Value "%s" invalid for option "%s" (%s)\n}; die sprintf $errfmt, $sex, "-s", "M or F expected" if length $sex and $sex =~ /^[^MF]$/; die sprintf $errfmt, $name, "-n", "first character can't be a hyphen" if length $name and $name =~ /^-/; print "[$name] [$age] [$sex] @ARGV\n"; -- Chas. Owens wonkden.net The most important skill a programmer can have is the ability to read. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/