您的位置:首页 > 运维架构

Getopt::Std模块的使用

2009-05-08 14:33 176 查看
 Getopt::Std模块的使用:

初始设置:  

在程序中加入如下代码:

          use Getopt::Std;

               use vars qw($opt_d $opt_f $opt_p);

               getopts('d:f:p');

               (注意上两行的参数要对应)

[ 解释一下"d:f:p",d和f后有冒号,表示-d,-f后面要跟参数。p后面没有冒号,表示-p后面不带参数。

而且-d,-f后所跟的参数分别赋给变量$opt_d和$opt_f。对于变量$opt_p,若命令行加了-p,则$opt_p=1,否则为0]

举个例子就很清楚了:

vi file.pl

添加如下代码:

use Getopt::Std;

use vars qw($opt_d $opt_f $opt_p);

getopts('d:f:p');

print "/$opt_d =>; $opt_d/n" if $opt_d;

print "/$opt_f =>; $opt_f/n" if $opt_f;

print "/$opt_p =>; $opt_p/n" if $opt_p;

然后在命令行中运行:

perl file.pl -d 20040412 -f louiskoochen -p

可得到下列形式的输出:

$opt_d =>;200040412

$opt_f =>;louiskoochen

$opt_p =>;1

 

use Getopt::Std;

getopt('oDI');    # -o, -D & -I take arg.  Sets $opt_* as a side effect.
getopt('oDI', /%opts);    # -o, -D & -I take arg.  Values in %opts
getopts('oif:');  # -o & -i are boolean flags, -f takes an argument
# Sets $opt_* as a side effect.
getopts('oif:', /%opts);  # options as above. Values in %opts


DESCRIPTION

The getopt() function processes single-character switches with switch
clustering. Pass one argument which is a string containing all switches
that take an argument. For each switch found, sets $opt_x (where x is the
switch name) to the value of the argument if an argument is expected,
or 1 otherwise. Switches which take an argument don't care whether
there is a space between the switch and the argument.

The getopts() function is similar, but you should pass to it the list of all
switches to be recognized. If unspecified switches are found on the
command-line, the user will be warned that an unknown option was given.
The getopts() function returns true unless an invalid option was found.

Note that, if your code is running under the recommended
use strict
'vars'

pragma, you will need to declare these package variables
with "our":

our($opt_x, $opt_y);

For those of you who don't like additional global variables being created, getopt()
and getopts() will also accept a hash reference as an optional second argument.
Hash keys will be x (where x is the switch name) with key values the value of
the argument or 1 if no argument is specified.

To allow programs to process arguments that look like switches, but aren't,
both functions will stop processing switches when they see the argument
--

. The
--

will be removed from @ARGV.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息