Question

Is it OK to keep options with undefined values (in this case 'maxdepth')?

#!/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;

Or should I write it like this:

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

Solution

There should be no problem in having maxdepth set to undef by using a variable with undef as its value. Every variable in Perl starts out with the undef value.

More Details

File::Find::Rule::LibMagic extends File::Find::Rule. The find function in File::Find::Rule starts with:

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

The new functions returns:

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

Note that maxdepth by default is set to undef.

OTHER TIPS

OK? It probably won't confuse 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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top