2

是否可以保留未定义值的选项(在本例中为“最大深度”)?

#!/usr/bin/env perl
use warnings;
use 5.012;
use File::Find::Rule::LibMagic qw(find);
use Getopt::Long qw(GetOptions);

my $max_depth;
GetOptions ( 'max-depth=i' => \$max_depth );
my $dir = shift;

my @dbs = find( file => magic => 'SQLite*', maxdepth => $max_depth, in => $dir );
say for @dbs;

或者我应该这样写:

if ( defined $max_depth ) {
    @dbs = find( file => magic => 'SQLite*', maxdepth => $max_depth, in => $dir );
} else {
    @dbs = find( file => magic => 'SQLite*', in => $dir );
}
4

2 回答 2

6

通过使用变量作为其值来maxdepth设置应该没有问题。Perl 中的每个变量都以值开头。undefundefundef

更多细节

File::Find::Rule::LibMagic延伸File::Find::Rule。中的find函数File::Find::Rule以:

sub find {
    my $object = __PACKAGE__->new();

new函数返回:

bless {
    rules    => [],
    subs     => {},
    iterator => [],
    extras   => {},
    maxdepth => undef,
    mindepth => undef,
}, $class;

请注意,maxdepth默认情况下设置为undef.

于 2012-02-05T15:42:36.743 回答
1

好的?它可能不会混淆 File::Find::Rule

$ perl -MFile::Find::Rule -le " print for File::Find::Rule->maxdepth(undef)->in( q/tope/ ) "
tope
tope/a
tope/b
tope/c
tope/c/0
tope/c/1
tope/c/2

$ perl -MFile::Find::Rule -le " print for File::Find::Rule->maxdepth(1)->in( q/tope/ ) "
tope
tope/a
tope/b
tope/c

$ perl -MFile::Find::Rule -le " print for File::Find::Rule->maxdepth(-1)->in( q/tope/ ) "
tope

$ perl -MFile::Find::Rule -le " print for File::Find::Rule->maxdepth(2)->in( q/tope/ ) "
tope
tope/a
tope/b
tope/c
tope/c/0
tope/c/1
tope/c/2

$ pmvers File::Find::Rule
0.33
于 2012-02-05T15:41:53.583 回答