Perl getopts Howto
This howto comes with no guaratees other than the fact that these code segments were copy/pasted from code that I wrote and ran successfully.
<style type="text/css"> <!-- .pod PRE { background : #eeeeee; border : 1px solid #888888; color : black; padding-top : 1em; white-space : pre; } .pod H1, H2 { background : transparent; color : #ff7300; } --></style>Process options passed to a program using getopts().
Make a global hash to store the options. Use the standard Getopt module. Make a string of one-character options. A character preceeding a colon takes an argument. The getopts function takes two arguments: a string of options, and a hash reference. For each command line option (aka switch) found, getopts sets $opt{x} (where x is the switch name) to the value of the argument, or 1 if no argument was provided.
Example
#
# Globals
#
use vars qw/ %opt /;
#
# Command line options processing
#
sub init()
{
use Getopt::Std;
my $opt_string = 'hvdf:';
getopts( "$opt_string", \%opt ) or usage();
usage() if $opt{h};
}
#
# Message about this program and how to use it
#
sub usage()
{
print STDERR << "EOF";
This program does...
usage: $0 [-hvd] [-f file]
-h : this (help) message
-v : verbose output
-d : print debugging messages to stderr
-f file : file containing usersnames, one per line
example: $0 -v -d -f file
EOF
exit;
}
init();
print STDERR "Verbose mode ON.\n" if $opt{v};
print STDERR "Debugging mode ON.\n" if $opt{d};
AUTHOR
Alex BATKO <abatko AT cs.mcgill.ca>
本文档介绍如何使用 Perl 的 getopts 模块来处理命令行参数。通过定义全局哈希来存储选项,并利用 Getopt::Std 模块解析命令行参数。示例代码展示了如何设置单字符选项及带参数的选项。
998

被折叠的 条评论
为什么被折叠?



