简体   繁体   English

Perl命令行参数

[英]Perl command line arguments

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. 我不确定如何在Perl中处理命令行参数,并希望有人可以指出我的正确方向。

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? 用这种格式提取参数的好方法是什么?

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: 但是,参数处理通常应使用Getopt::Long模块完成:

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)

Eg invoked as script.pl --ts=Ts --life=2 --ts=Age --life=2 例如作为script.pl --ts=Ts --life=2 --ts=Age --life=2

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

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