標籤:
來源:
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 string11 sub parse_opts{12 my $result = GetOptions(13 "optionA=s" => \$g_opts->{‘optionA‘},#string14 "optionB=s" => \$g_opts->{‘optionB‘},#string15 "optionC=i" => \$g_opts->{‘optionC‘},#integer16 "optionD=f" => \$g_opts->{‘optionD‘},#float17 "optionX=f" => \$optionX,18 "optionY=f" => \$optionY,19 "verbose" => \$g_opts->{‘verbose‘},#flag20 "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 125 }26 if($g_opts->{‘help‘}){27 &pod2usage( -verbose => 1);#exit status will be 128 }29 }30 31 &parse_opts();32 print("\n$optionX\n");33 print($optionY); #if not defined in command line, it will be undefined34 print($g_opts->{"optionB"});35 36 foreach my $key (keys %{$g_opts}){37 if(!$g_opts->{$key}) {next;} 38 print($key . "=" . $g_opts->{$key} . "\n");39 }40 41 exit(0);42 43 44 45 __END__46 47 =head1 NAME48 49 sample - Using Getopt::Long and Pod::Usage50 51 =head1 SYNOPSIS52 53 sample [options] [args ...]54 55 Options:56 57 -optionA optionA 58 -optionB optionB59 -optionC optionC 60 -optionD optionD 61 -verbose verbose 62 -quiet noverbose 63 -help brief help message64 65 =head1 OPTIONS66 67 =over 868 69 =item B<-help>70 71 Print a brief help message and exits.72 73 =back74 75 =head1 DESCRIPTION76 77 B<This program> will read the given input file(s) and do something78 useful with the contents thereof.79 80 =cut
perl的Getopt::Long和pod::usage ?