For example, do you call it with "-t" or with "-t 1"? There is a difference.
I have added some print statements to your code to help debug:
> cat 714766.pl #!/usr/bin/env perl use strict; use warnings; use Data::Dumper; use Getopt::Std; #print 'ARGV ',Dumper(\@ARGV); my $test = 1; my %opt; getopt('st',\%opt); #print 'opt ',Dumper(\%opt); if ($opt{'t'}) { $test = 1; ## testing #print "set test=1 again\n"; } elsif ($opt{'s'}) { $test = 0; ## not testing #print "set test=0\n"; } #print "test=$test\n"; if ( (!(defined($opt{'s'}))) && (!(defined($opt{'t'}))) ) { print "neither -t or -s used\n"; } else { print "either -t or -s used\n"; }
Now some sample program calls (5.8.8 on linux):
> ./714766.pl neither -t or -s used > > ./714766.pl -t neither -t or -s used > > ./714766.pl -t 0 either -t or -s used > > ./714766.pl -t 1 either -t or -s used > > ./714766.pl -s 5 either -t or -s used
Data::Dumper can help you understand what is in %opt
Update: It seems to me that the documentation for Getopt::Std is incorrect:
getopt() and getopts() will also accept a hash reference as an optional second argument. Hash keys will be x (where x is the switch name) with key values the value of the argument or 1 if no argument is specified.If no argument is specified for getopt, the hash key is NOT set to 1 (Dumper shows it as 'undef').
In reply to Re: Detecting an undefined hash key
by toolic
in thread Detecting an undefined hash key
by LesleyB
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |