2

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 );
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
sid_com
  • 24,137
  • 26
  • 96
  • 187
  • This question is about [File::Find::Rule::LibMagic](https://metacpan.org/module/File::Find::Rule::LibMagic). This should appear more clearly in the title. – dolmen Feb 06 '12 at 14:04
  • I added `File::Find::Rule::LibMagic` in the title. But my interest was more general - but maybe it is different from module to module. – sid_com Feb 06 '12 at 14:44

2 Answers2

6

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.

Alan Haggai Alavi
  • 72,802
  • 19
  • 102
  • 127
1

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
obmib
  • 466
  • 2
  • 6