Reputation: 43
I'm not sure how to go about processing command line arguments in Perl and was hoping someone could point my in the right direction.
My script will take arguments like this:
$perl my_script.pl server1_life=2 server1_ts=Ts server2_life=2 server2_ts=Age
The script needs to be able to extract the 'life' and timestamp values for each server. Currently I am storing the arguments in an array.
What is a good way to extract arguments in this format?
Upvotes: 1
Views: 1504
Reputation: 57590
Well, one can always parse the arguments manually. Here, we want to split each argument at =
and probably store the results in a hash:
my %server_configs = map { split /=/, $_, 2 } @ARGV;
#=> (
# server1_life => 2,
# server1_ts => "Ts",
# server2_life => 2,
# server2_ts => "Age",
# )
However, argument handling should usually be done with the Getopt::Long
module:
use Getopt::Long;
my %args;
GetOptions(\%args, 'life=i@', 'ts=s@');
# combine the config parts for each server
my @server_configs = map { [$args{ts}[$_], $args{life}[$_]] } 0 .. $#{ $args{ts} };
#=> ( [Ts => 2], [Age => 2] )
# or:
my %server_configs;
@server_configs{@{ $args{ts} }} = @{ $args{life} };
#=> (Ts => 2, Age => 2)
E.g. invoked as script.pl --ts=Ts --life=2 --ts=Age --life=2
Upvotes: 4