vincentaxhe has asked for the wisdom of the Perl Monks concerning the following question:

I have script getfiles.pl with code like that
my %options; getopts("r:", \%options); ... $regex = qr($options{r}); foreach (@files){ my $filepath = $_->[0]; if ($filepath =~ $regex){ push @matched, $filepath; } }
I run getfiles.pl -r 'python' filelist to filter filepath containing 'python' but I also want to run like getfiles.pl -e '-d' listfile to get files which are dirs or getfiles.pl -e '-s > 100' filelist and more such as -t -M.
my %options; getopts("e:", \%options); ... $wanted = qr($options{e}); sub getwanted(&@){ my ($wanted, $file) return 1 if $wanted->($file) ... } foreach (@files){ $filepath = $_->[0]; if (getwanted $wanted $filepath){ push @matched, $filepath; } }
but the subroutine is not good, ask some advice

Replies are listed 'Best First'.
Re: use -d -t -s as script args
by ikegami (Patriarch) on Jun 21, 2024 at 16:09 UTC

    To evaluate Perl code, you need to pass it to perl, or use eval EXPR or require or do.

    eval EXPR is what you want here.

      I figure it out
      my $code = "sub is_wanted { " . join(" and ", @ARGV) . " } "; unless (eval $code.1) { die "Error in code: $@\n\t$code\n"; } $_ = $filepath; if (is_wanted()){ push @matched, $filepath; }
        um, do it safely, don't use @ARGV directly