简体   繁体   English

如果没有提供选项,运行子程序的最佳方法是什么? Perl getOpt

[英]Best way to run subroutine if no options provided? Perl getOpt

For example, 例如,

If I run 如果我跑

./program -i 

do subA 做subA

if I run 如果我跑

./program 

do subB 做subB

my code currently looks like this 我的代码目前看起来像这样

subB if(!$opt_a && !$opt_b && !opt_b);

but this looks messy. 但这看起来很乱。 Is there anyway to make it run subB if no options provided rather than check each individual option? 如果没有提供选项而不是检查每个选项,有没有让它运行subB?

You can store the options in a hash and check to see if the hash evaluates to true or false: 您可以将选项存储在哈希中,并检查哈希是否计算为true或false:

use strict;
use warnings;

use Getopt::Long;

my %options;
GetOptions( \%options, 'opt_a=i', 'opt_b', 'opt_c' );

if ( %options ) {

    # Season with option validation ..
    # Usage : $options{opt_a} instead of $opt_a

    subA();
}

else {

    subB();
}

I sometimes use a delete hash idiom when a tool only operates on one (or specific combinations) of options so that I can let the user know if everything was consumed as expected. 当工具仅对选项的一个(或特定组合)进行操作时,我有时会使用删除哈希习语,以便我可以让用户知道是否所有内容都按预期消耗。 Update: just replace the print statements with your sub calls. 更新:只需用子调用替换print语句。

use strictures;
use Getopt::Long;

GetOptions( \my %opt, "int=i", "str=s", "bool" );

print "OPTIONS, I HAZ DEM\n" if %opt;

if ( delete $opt{int} )
{
    print "* I HAZ A INT\n";
}
elsif ( delete $opt{str} )
{
    print "* I HAZ STRING\n";
}
elsif ( delete $opt{bool} )
{
    print "* I HAZ A TRUTH\n";
}
else
{
    print "I CAN HAZ OPTION?\n";
}

print "DO NOT WANT: ", join(", ", keys %opt), $/
    if %opt;

I'd check each individual option anyway. 无论如何,我会检查每个选项。 It makes things much clearer for whoever has to modify the program in three years time... and it might even be you. 对于那些需要在三年内修改程序的人来说,它更加清晰......甚至可能是你。

Bite the bullet and code it in full. 咬紧牙关并完整编码。 Its tedious but saves time in the long run. 它繁琐但从长远来看节省时间。

    if ($opt_a) 
  {
    # do whatever
  }
elsif ($opt_b)      
  {
    # do whatever
  }
else
  {
    # default behaviour if no arguments passed from command line
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM