Search code examples
perlcommand-line-argumentsoptional-parametersfile-find

File::Find::Rule::LibMagic: Is it ok to keep options with undefined values?


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 );
}

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.