David B
David B

Reputation: 29988

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 convert all of these into some standard structure (hash) instead of parsing?

Thanks, Dave

Upvotes: 0

Views: 1028

Answers (2)

daxim
daxim

Reputation: 39158

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

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

Upvotes: 1

Vinko Vrsalovic
Vinko Vrsalovic

Reputation: 340211

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

Upvotes: 8

Related Questions