用傳統(tǒng)的 Unix 方式創(chuàng)建的簡(jiǎn)單用戶界面
Unix 用戶非常熟悉基于文本的 UI 模型。設(shè)想有一個(gè) Perl
程序,讓我們先看一下這個(gè)模型用于該程序的簡(jiǎn)單實(shí)現(xiàn)。標(biāo)準(zhǔn)的 Getopt::Std
模塊簡(jiǎn)化了命令行參數(shù)的解析。這個(gè)程序僅僅為了說明 Getopt::Std 模塊(沒有實(shí)際用途)。
請(qǐng)參閱本文后面的參考資料。
使用 Getopt::Std 的命令行開關(guān)
#!/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;
}