来源:
http://www.cnblogs.com/itech/archive/2012/08/07/2627267.html
代码:
需要显式地定义变量且初始化。例如optionX。
如果没有定义变量且显式初始化,且没有在命令行指定选项,则选项对应的变量将为未定义。
1 #!/bin/perl-5.8.3/bin/perl$ 2 use warnings; 3 use strict; 4 5 use Data::Dumper; 6 use Getopt::Long; 7 use Pod::Usage; 8 9 our $g_opts; 10 our $optionX=''; #if not defined in command line, it will be empty string 11 sub parse_opts{ 12 my $result = GetOptions( 13 "optionA=s" => $g_opts->{'optionA'},#string 14 "optionB=s" => $g_opts->{'optionB'},#string 15 "optionC=i" => $g_opts->{'optionC'},#integer 16 "optionD=f" => $g_opts->{'optionD'},#float 17 "optionX=f" => $optionX, 18 "optionY=f" => $optionY, 19 "verbose" => $g_opts->{'verbose'},#flag 20 "quiet" => sub { $g_opts->{'verbose'} = 0 }, 21 "help|?" => $g_opts->{'help'} 22 ); 23 if(!($g_opts->{'optionA'})){ 24 &pod2usage( -verbose => 1);#exit status will be 1 25 } 26 if($g_opts->{'help'}){ 27 &pod2usage( -verbose => 1);#exit status will be 1 28 } 29 } 30 31 &parse_opts(); 32 print(" $optionX "); 33 print($optionY); #if not defined in command line, it will be undefined 34 print($g_opts->{"optionB"}); 35 36 foreach my $key (keys %{$g_opts}){ 37 if(!$g_opts->{$key}) {next;} 38 print($key . "=" . $g_opts->{$key} . " "); 39 } 40 41 exit(0); 42 43 44 45 __END__46 47 =head1 NAME 48 49 sample - Using Getopt::Long and Pod::Usage 50 51 =head1 SYNOPSIS 52 53 sample [options] [args ...] 54 55 Options:56 57 -optionA optionA 58 -optionB optionB 59 -optionC optionC 60 -optionD optionD 61 -verbose verbose 62 -quiet noverbose 63 -help brief help message 64 65 =head1 OPTIONS 66 67 =over 868 69 =item B<-help>70 71 Print a brief help message and exits.72 73 =back 74 75 =head1 DESCRIPTION 76 77 B<This program> will read the given input file(s) and do something 78 useful with the contents thereof.79 80 =cut