用传统的 Unix 方式创建的简单用户界面
Unix 用户非常熟悉基于文本的 UI 模型。设想有一个 Perl
程序,让我们先看一下这个模型用于该程序的简单实现。标准的 Getopt::Std
模块简化了命令行参数的解析。这个程序仅仅为了说明 Getopt::Std 模块(没有实际用途)。
请参阅本文后面的参考资料。
使用 Getopt::Std 的命令行开关
#!/usr/bin/perl -w
use strict; # always use strict, it's a good habit
use Getopt::Std; # see "perldoc Getopt::Std"
my %options;
getopts('f:hl', \%options); # read the options with getopts
# uncomment the following two lines to see what the options hash contains
#use Data::Dumper;
#print Dumper \%options;
$options{h} && usage(); # the -h switch
# use the -f switch, if it's given, or use a default configuration filename
my $config_file = $options{f} || 'first.conf';
print "Configuration file is $config_file\n";
# check for the -l switch
if ($options{l})
{
system('/bin/ls -l');
}
else
{
system('/bin/ls');
}
# print out the help and exit
sub usage
{
print <<EOHIPPUS;
first.pl [-l] [-h] [-f FILENAME]
Lists the files in the current directory, using either /bin/ls or
/bin/ls -l. The -f switch selects a different configuration file.
The -h switch prints this help.
EOHIPPUS
exit;
}