Perl常用模块Getopt::Long——获取用户命令行参数


        Perl脚本中经常需要获取用户命令行参数来选择不同的功能,翻看了下

公司SoC仿真环境的一些脚本,基本上都要用到Getopt::Long模块来得到用

户命令行参数,选取不同参数实现不同功能。使用perldoc Getopt::Long能

得到详细的模块使用信息,如果只是简单使用的话看下面的用法基本上够用了。

 1 #!  /usr/bin/perl  w
 2 #=================
 3 #Used Modules
 4 #=================
 5 use strict;
 6 use Getopt::Long;
 7 $Getopt::Long::ignorecase = 0;
 8 
 9 my $g_code_mem;
10 
11 #Get option from command line
12 my %Opt;
13 if(!GetOptions(
14     \%Opt,
15     '--codemem=i',   #1 ROM 1, 2: SRAM
16     '--h', #print help message
17 )){
18    &print_usage();
19    exit(1);
20 }
21 
22 #if '-h',the help message will be printed
23 if($Opt{'h'}){
24   &print_usage();
25   exit(1);
26 }
27 
28 if(defined $Opt{'codemem'}){
29   if($Opt{'codemem'} == 1)
30     $g_code_mem = 'ROM';
31   else if($Opt{'codemem'} == 2)
32     $g_code_mem = 'SRAM';
33   else{
34      print "Parameter 'codemem' only can be configured to 1 or 2\n";
35      exit;
36   }
37 }
38 
39 sub print_usage{
40   print << Usage: getopt [options]
41   [options] = 
42   [-h]            prints this message
43   [-codemem=i]  i=1 ROM,i=2 SRAM
44 }

用的时候注意一点,用户有可能会输入了选项而没有输入参数或输入空格,这

两种特殊情况也要考虑进去,可以先做一个判断:if(!($Opt{'mode'}|| ($Opt{'mode'} eq ' '))

然后告诉用户输入正确的参数。