下面的代码演示了两种方法来实现你想要的。
“本土”方法使用 map 和 join 来生成选项列表。(grep 消除了 undef 选项。您可以删除 grep {} 部分。)
Data::Dumper 方法可能是可取的,因为它是可评估的。
#!/usr/bin/env perl
use strict;
use warnings;
use Getopt::Long qw(:config gnu_getopt);
use Data::Dumper;
$Data::Dumper::Sortkeys = 1;
$Data::Dumper::Indent = 0;
$Data::Dumper::Terse = 1;
my %opts = (
dir => undef,
verbose => 0,
silent => 0,
);
GetOptions(\%opts,
'dir|d=s',
'verbose|v+',
'silent+',
)
or die("Usage: blah\n");
# also see Getopt::Long perldoc for pod2usage
print( "home grown:\n",
join(" ", map { sprintf('%s=>%s',$_,$opts{$_}||'undef') }
grep {defined $opts{$_}} keys %opts ),
"\n" );
print( "Dumper:\n",
Dumper(\%opts),
"\n" );
例子:
apt12j$ ~/tmp/x.pl -vv --silent
home grown:
verbose=>2 silent=>1
Dumper:
{'dir' => undef,'silent' => 1,'verbose' => 2}