in reply to How to generate Perl statements on the fly and execute them when they are synthesized.

I would recommend that you avoid eval when there are alternatives for the same reason that people are taught to avoid goto. Namely the freedom which results is such that it makes your code harder to understand. Also when you use eval, you need to worry about the fact that it traps errors, so slight mistakes can turn into errors which (if you have not coded the error handling just right) you might miss.

For instance in this case you can use some loop control to solve the actual problem. Consider:

# Takes a string and a list of REs. Returns true or false # depending on whether all of them match. sub match_all { my $str = shift; foreach my $re (@_) { return 0 unless $str =~ /$re/; } return 1; }
Note the my in there. That is necessary if you are working with strict.pm, which is a habit I strongly recommend. The time spent not tracking down typos makes it highly worthwhile.

And then you would use this as follows:

if (match_all($str, split(/\s+/, $search_str))) { print "All of them matched\n"; }
(Note. Using /\Q$re\E/ for the match will handle strange characters in it, but would block using REs compiled with qr//. Choose, freedom or error handling?)

Also you could achieve the same effect with nested loop and loop control:

OUTER: { foreach my $animal (@animals) { last OUTER if $str !~ /$animal/; } print "Matched all of them!"; }
  • Comment on Re (tilly) 1: How to generate Perl statements on the fly and execute them when they are synthesized.
  • Select or Download Code