获取命令行选项及其值
我想在运行脚本后记录用户命令的选项及其参数。
考虑这个命令:
./test.pl --ip localhost --id 400154 --class firstgrade
...以及许多其他选项和值。我想要的输出是这样的(通过使用 log4perl):
debug - ip=>localhost id=>400154 class=>firstgrade
我这样做:
use Getopt::Long;
my $ip;
my $id;
my $class;
my %h =('ip' => \$ip,
'id' => \$id,
'class' => \$class);
GetOptions(\%h);
$logger->debug(join('=>',%h));
但它不起作用。请帮忙。
I want to log options and their arguments from user command after running the script.
Consider this command:
./test.pl --ip localhost --id 400154 --class firstgrade
...and many other options and values. My desired output would be like this(by using log4perl):
debug - ip=>localhost id=>400154 class=>firstgrade
I do:
use Getopt::Long;
my $ip;
my $id;
my $class;
my %h =('ip' => \$ip,
'id' => \$id,
'class' => \$class);
GetOptions(\%h);
$logger->debug(join('=>',%h));
but it doesn't work. Please help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的代码是 Getopt::Long 的两个不同功能的奇怪组合 - 它可以将选项解析为散列或将单个选项填充到变量中。甚至可以将一部分放入哈希中,将其余部分放入变量中。
这应该可行:
这是将解析的选项放入哈希中的变体。请注意每个选项后面的
:s
以指示它需要一个参数。编辑:根据下面的澄清更新了答案。
Your code is weird combination of two distinct features of
Getopt::Long
- it can either parse options into hash or fill individual options into variables. It is even possible to put part into hash and rest into variables.This should work:
This is variant where parsed options are put into the hash. Note
:s
after each option to indicate that it takes an argument.Edit: updated the answer per clarification below.
试试这个:
你可能应该这样称呼它:
Try this:
And you should probably call it like this:
以下代码演示了两种实现您想要的效果的方法。
“自行开发”方法使用映射和连接来生成选项列表。 (grep 消除了 undef 选项。您可以删除 grep {} 部分。)
Data::Dumper 方法可能是理想的,因为它是可评估的。
例子:
The following code demonstrates two ways to achieve what you want.
The 'home grown' method uses map and join to generate the options list. (The grep eliminates undef options. You can remove the grep {} part.)
The Data::Dumper method may be desirable because it's eval-able.
Example:
查看 MooseX::Getopt,它将为您提供双重帮助:
让您了解现代 OO Perl
创建超级简单的命令行应用程序。
查看 MooseX::App::Cmd。它也将帮助您分离出您的逻辑。或者如果您还不想喝 Moose kool-aid,请使用 App::Cmd。
Checkout MooseX::Getopt, it'll help you two-fold:
get you into modern OO perl
create super simple command line apps.
Checkout MooseX::App::Cmd. It'll help you separate your logic out as well. Or App::Cmd if you don't want to drink the Moose kool-aid just yet.