haukex and choroba are both wise and right about possibly dangerous uses of eval but since you are asking the user to enter a regex you must be sure that is a valid one; infact your code allows to pass a wrong regex:
Gimme a string: a Gimme a RegEx: a( Unmatched ( in regex; marked by <-- HERE in m/a( <-- HERE / at .. line + .. <STDIN> line 2.
So sometimes eval is useful and imho one these cases is compiling a regex (see qr// in perl documentation):
use strict; use warnings; print "Gimme a string: "; my $str = <STDIN>; chomp $str; print "Gimme a RegEx: "; my $pattern = <STDIN>; chomp $pattern; my $rex; { # a block to localize $@ local $@; # eval the regex eval{ $rex = qr/$pattern/ }; # die if errors die "error compiling regex!" if $@; } # end of the localizing block print $str =~ /$rex/ ? "Yes!" : "No.";
So do not avoid eval because it can be dangerous: know it and profit it! Obviously you do not use a bazooka to kill a mosquito.. do you?
PS about arbitrary code execution I was tempted to add also regex can lead to code execution but perl is wise in this: not arbitrary code:
L*perl -E "say 'match' if 'ec' =~ /$ARGV[0]/" "ec(?{print 'EVAL!';})" Eval-group not allowed at runtime, use re 'eval' in regex m/ec(?{print + 'EVAL!';})/ at -e line 1.
In reply to Re: Idiomatic Perl? -- eval qr/ /
by Discipulus
in thread Idiomatic Perl?
by thenextfart
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |