猿问

刚刚学perl,就遇到了GetOptions,请问下面代码什么意思?

$gh_prog_opt{"spxml"} = "imirel_sp.xml";
$gh_prog_opt{"relxml"} = "imirel.xml";
$gh_prog_opt{"corexml"} = "imirel_core.xml";
my $g_optcheck_success = GetOptions(\%$gh_prog_opt, qw(help|h relxml|r=s spxml|s=s corexml|c=s)); 这句话什么意思?

素胚勾勒不出你
浏览 308回答 1
1回答

慕哥9229398

GetOptions(\%gh_prog_opt, qw(help|h relxml|r=s spxml|s=s corexml|c=s));可以读入指定的命令行参数设置到gh_prog_opt散列中;-h等价于-help,相当于别名,类似的-r是-relxml的别名,-s是-spxml的别名,-c是-corexml的别名;=s表示要用等号再跟一个字符串值类似的还有i表示需要整数值,f表示需要浮点数值,=(=s或=i等)表示该参数必须跟值,还有:(:s或:i等)表示该参数可以跟值,如果命令行没有跟值,则设置为空字符串或数字0。更详细的用法可以在命令行中执行 perldoc Getopt::Long 查看(如果您英语好),或是上网查找GetOptions的用法。另外,我感觉您程序中“GetOptions(\%$gh_prog_opt”可能多了个美元号。以下是测试程序代码,希望能帮助您理解GetOptions的用法:use Getopt::Long;use Data::Dumper;$gh_prog_opt{"spxml"} = "imirel_sp.xml";$gh_prog_opt{"relxml"} = "imirel.xml";$gh_prog_opt{"corexml"} = "imirel_core.xml";my $g_optcheck_success = GetOptions(\%gh_prog_opt, qw(help|h relxml|r=s spxml|s=s corexml|c=s));print Dumper(\%gh_prog_opt);保存以上代码到文件 test.pl若命令行执行 perl test.pl输出结果:$VAR1 = {'corexml' => 'imirel_core.xml','relxml' => 'imirel.xml','spxml' => 'imirel_sp.xml'};即表示初始默认值 $gh_prog_opt{"spxml"} = "imirel_sp.xml" 等若命令行执行 perl test.pl -h输出结果:$VAR1 = {'corexml' => 'imirel_core.xml','relxml' => 'imirel.xml','spxml' => 'imirel_sp.xml','help' => 1};即增加了 $gh_prog_opt{"help"} = 1若命令行执行 perl test.pl -h=2输出结果:Option h does not take an argument$VAR1 = {'corexml' => 'imirel_core.xml','relxml' => 'imirel.xml','spxml' => 'imirel_sp.xml'};即-help参数不能再跟值,是个bool型参数若命令行执行 perl test.pl -c输出结果:Option c requires an argument$VAR1 = {'corexml' => 'imirel_core.xml','relxml' => 'imirel.xml','spxml' => 'imirel_sp.xml'};即-c(就是-corexml)参数需要跟一个字符串值若命令行执行 perl test.pl -c=c_file输出结果:$VAR1 = {'corexml' => 'c_file','relxml' => 'imirel.xml','spxml' => 'imirel_sp.xml'};即设置了 $gh_prog_opt{"corexml"} = "c_file"若命令行执行 perl test.pl -cor输出结果:Option corexml requires an argument$VAR1 = {'corexml' => 'imirel_core.xml','relxml' => 'imirel.xml','spxml' => 'imirel_sp.xml'};即-corexml可以简写为-cor若命令行执行 perl test.pl -cor=cor_file输出结果:$VAR1 = {'corexml' => 'cor_file','relxml' => 'imirel.xml','spxml' => 'imirel_sp.xml'};若命令行执行 perl test.pl -corexml=cor_file输出结果:$VAR1 = {'corexml' => 'cor_file','relxml' => 'imirel.xml','spxml' => 'imirel_sp.xml'};若命令行执行 perl test.pl -corexml2=cor_file输出结果:Unknown option: corexml2$VAR1 = {'corexml' => 'imirel_core.xml','relxml' => 'imirel.xml','spxml' => 'imirel_sp.xml'};即不能识别-corexml2参数若命令行执行 perl test.pl -c=1 -r=2 -s=3输出结果:$VAR1 = {'corexml' => '1','relxml' => '2','spxml' => '3'};即设置了 $gh_prog_opt{"corexml"} = "1" 等
随时随地看视频慕课网APP
我要回答