1#!./perl -wT 2 3BEGIN { 4 chdir 't' if -d 't'; 5 @INC = '../lib'; 6} 7 8use strict; 9use warnings; 10 11use Test::More; 12use Getopt::Std; 13 14our ($warning, $opt_f, $opt_i, $opt_o, $opt_x, $opt_y, %opt); 15 16# First we test the getopt function 17@ARGV = qw(-xo -f foo -y file); 18getopt('f'); 19 20is( "@ARGV", 'file', 'options removed from @ARGV (1)' ); 21ok( $opt_x && $opt_o && $opt_y, 'options -x, -o and -y set' ); 22is( $opt_f, 'foo', q/option -f is 'foo'/ ); 23 24@ARGV = qw(-hij k -- -l m -n); 25getopt 'il', \%opt; 26 27is( "@ARGV", 'k -- -l m -n', 'options removed from @ARGV (2)' ); 28ok( $opt{h} && $opt{i} eq 'j', 'option -h and -i correctly set' ); 29ok( !defined $opt{l}, 'option -l not set' ); 30ok( !defined $opt_i, '$opt_i still undefined' ); 31 32# Then we try the getopts 33$opt_o = $opt_i = $opt_f = undef; 34@ARGV = qw(-foi -i file); 35 36ok( getopts('oif:'), 'getopts succeeded (1)' ); 37is( "@ARGV", 'file', 'options removed from @ARGV (3)' ); 38ok( $opt_i && $opt_f eq 'oi', 'options -i and -f correctly set' ); 39ok( !defined $opt_o, 'option -o not set' ); 40 41%opt = (); $opt_i = undef; 42@ARGV = qw(-hij -k -- -l m); 43 44ok( getopts('hi:kl', \%opt), 'getopts succeeded (2)' ); 45is( "@ARGV", '-l m', 'options removed from @ARGV (4)' ); 46ok( $opt{h} && $opt{k}, 'options -h and -k set' ); 47is( $opt{i}, 'j', q/option -i is 'j'/ ); 48ok( !defined $opt_i, '$opt_i still undefined' ); 49 50# Try illegal options, but avoid printing of the error message 51$SIG{__WARN__} = sub { $warning = $_[0] }; 52@ARGV = qw(-h help); 53 54ok( !getopts("xf:y"), 'getopts fails for an illegal option' ); 55ok( $warning eq "Unknown option: h\n", 'user warned' ); 56 57# Tests for RT #41359 58undef %opt; 59my $expected; 60{ 61 local @ARGV = ( '-a', '-b', 'foo', '-c' ); 62 getopts('ab:c:', \%opt); 63 $expected = { 'a' => 1, 'b' => 'foo', 'c' => undef }; 64 is_deeply(\%opt, $expected, 65 "getopts: multiple switches; switch expected argument, none provided; value undef"); 66 undef %opt; 67} 68 69{ 70 local @ARGV = ( '-c' ); 71 getopts('c:', \%opt); 72 $expected = { 'c' => undef }; 73 is_deeply(\%opt, $expected, 74 "getopts: single switch; switch expected argument, none provided; value undef"); 75 undef %opt; 76} 77 78{ 79 local @ARGV = ( '-b', 'foo', '-c' ); 80 getopt('bc', \%opt); 81 $expected = { 'b' => 'foo', 'c' => undef }; 82 is_deeply(\%opt, $expected, 83 "getopt: multiple switches; switch expected argument, none provided; value undef"); 84 undef %opt; 85} 86 87{ 88 local @ARGV = ( '-c' ); 89 getopt('c', \%opt); 90 $expected = { 'c' => undef }; 91 is_deeply(\%opt, $expected, 92 "getopt: single switch; switch expected argument, none provided; value undef"); 93 undef %opt; 94} 95 96done_testing(); 97