如何解析命令行参数?

Posted

技术标签:

【中文标题】如何解析命令行参数?【英文标题】:How can I parse command line arguments? 【发布时间】:2011-04-27 17:47:58 【问题描述】:

我想解析一个 perl 脚本中的参数列表,例如我有这种情况:

script.pl -h 127.0.0.1 -u user -p pass arg1 arg2 arg3

如何解析不是数组中选项的参数列表,以及标量值中的选项参数?

谢谢。

【问题讨论】:

Mastering Perl 中,我谈到了 90 多个 Perl 模块,它们让您几乎可以以任何您喜欢的方式完成此任务。 :) 【参考方案1】:

好吧,如果它们是命令行上唯一没有作为选项给出的东西,那么它们应该仍然在@ARGV 中。所以只需使用@ARGV

use Getopt::Long;

# save arguments following -h or --host in the scalar $host
# the '=s' means that an argument follows the option
# they can follow by a space or '=' ( --host=127.0.0.1 )
GetOptions( 'host=s' => \my $host 
          , 'user=s' => \my $user  # same for --user or -u
          , 'pass=s' => \my $pass  # same for --pass or -p
          );

# @ARGV: [ qw<arg1 arg2 arg3> ]

Getopt::Long

【讨论】:

【参考方案2】:

程序的参数存储在@ARGV

如果您想对开关进行任何处理,请使用Getopt::Long,这是一个标准的 Perl 模块。

即使你认为“哦,我可以从列表中选择我想要的东西”,请使用Getopt::Long,因为我向你保证,你会添加更多开关的时间到了,你会结束的说“伙计,我希望我从一开始就开始使用 Getopt::Long。”

另请参阅我的博文"Use Getopt::Long even if you think you don't need it"。

【讨论】:

该链接已损坏(404) 谢谢,@Bogolt。我把它从 Wayback Machine 中挖出来,重新发布,并更新了链接。 实际上,更好地使用 argparse,它支持位置参数并且在我看来有一个更干净的界面

以上是关于如何解析命令行参数?的主要内容,如果未能解决你的问题,请参考以下文章

Python 命令行参数解析: optparse 模块

如何在 C# 中解析命令行参数 [重复]

Python笔记:命令行参数解析

27.Go 解析命令行参数

如何将(宽度)x(高度)命令行参数解析为两个参数?

如何在 C# 中解析 powershell 样式的命令行参数 [重复]