暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Perl: Getopt::Long模块 参数解析

伪书虫笔记 2021-09-23
1277

在芯片设计过程中,我们常常需要自己写一些脚本来实现某些功能,但是这些脚本往往也是团队中其他成员需要的,所以我们有时候需要分享我们写好的脚本给团队中的成员使用,或者让我们的脚本能够灵活一些,给定一些参数给脚本运行,这个时候我们就可以用到perl模块 Getopt::Long

====>>这里给出一个例子来简单解析一下这个模块:

----------------------------------------------------------------------------

#!/usr/bin/perl

use Getopt::Long;

###################################################### Parse all the command line option and make sure options are all valid.


$option = &GetOptions("h"=>\$help,

              "HldValue:i" =>\$HldValue,

              "IPName:s"  =>\$IPName,

);

##############################################################################

# Check for various errors in command line options.

if(!$option) {

    print "Invalid Options provided. Please check the options.\n\n";

    print "Please use '$0 -h' for help message.\n\n";

    exit;

}

##############################################################################

# Process the -h option and print usage information for user.

if(defined($help)) {&printHelp(); exit; }

##############################################################################

# Subroutine Name : printHelp

# Description     : prints a usage for this script

sub printHelp {

   my $e0s = sprintf("%*s",length($0),"");

   print "\n$0 [ -h ] [ -HldValue ] [ -IPName ]  \n";

   print "- hPrint this help message.\n\n";

   print "-IPName <i2c usb isp > .\n\n";

   print "-HldValue <-200 -300>.\n\n";

   print " will output file: design_qor_info.cvs \n";

}# end of printHelp

------------------------------------------------------------------------------

通过上面的蓝色部分我们可以看到,我们是通过一个选项列表来调用GetOptions模块,每个选项描述列表由两个元素组成:选项说明符("h")和选项链接(=>\$help)。选项说明符定义了选项名称,以及它可以接受的值,选项链接通常是对将在使用选项时设置的变量的引用,例如上面的例子,我在使用该脚本时 xxx.pl -HldValue -200 -IPName usb


'h'只有单独的一个选项,不接受任何参数。在命令行用--h
来触发,触发后$help
被设置为1,次用法常作为一个开关选项使用。

'IPName:s' 代表该选项接受一个可选的字符串参数,这个字符串将被赋值给option变量,如果省略,它会被赋值为“”(一个空字符串)。如果字符串参数以-或者--开头,它会被看成一个选项。



文章转载自伪书虫笔记,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论