开发者

How do I convert passed flags/arguments to my Perl program without parsing them myself?

I would like to pass a perl program a set of arguments and flags, e.g. my_script.pl --flag1 --arg1=value --flag2 …

Is there a way to quickly con开发者_C百科vert all of these into some standard structure (hash) instead of parsing?

Thanks, Dave


You should use Getopt::Long

Sample:

linux-t77m:/home/vinko # more opt.pl
use Getopt::Long;    
my $arg1 = 'default_value';
GetOptions('flag1' => \$flag1, 'arg1=s' => \$arg1, 'flag2' => \$flag2);    
print "FLAG1: ".$flag1." ARG1: ".$arg1." FLAG2: ".$flag2."\n\n";

linux-t77m:/home/vinko # perl opt.pl --flag2 --arg1=stack
FLAG1:  ARG1: stack FLAG2: 1

linux-t77m:/home/vinko # perl opt.pl --flag1 --flag2
FLAG1: 1 ARG1: default_value  FLAG2: 1


GetOptions also can fill a hash as requested in the question.

my %opt;
GetOptions(\%opt, qw(flag1 arg1=s flag2)) or pod2usage(2);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜