如何解析命令行参数? [英] How can I parse command line arguments?

查看:30
本文介绍了如何解析命令行参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

谢谢.

解决方案

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

使用 Getopt::Long;# 在标量 $host 中保存 -h 或 --host 后面的参数# '=s' 表示在选项后面有一个参数# 他们可以跟一个空格或 '=' ( --host=127.0.0.1 )GetOptions( 'host=s' => \my $host, '用户 = s' =>\my $user # --user 或 -u 相同, 'pass=s' =>\my $pass # --pass 或 -p 相同);# @ARGV: [ qw]

Getopt::Long

I want to parse a list of arguments in a perl script, for example i have this situation :

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

How can i do for parse the list of argument that aren't option in an array, and the option parameter in scalar value ?

Thanks.

解决方案

Well, if they are the only things on the command line that aren't given as options, then they should still be in @ARGV. So just use @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> ]

see Getopt::Long

这篇关于如何解析命令行参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆