Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Idiomatic Perl? -- eval qr/ /

by Discipulus (Canon)
on Mar 20, 2018 at 20:37 UTC ( [id://1211376]=note: print w/replies, xml ) Need Help??


in reply to Idiomatic Perl?

Hello thenextfrater and welcome to the monastery and to the wonderful world of Perl!

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:

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.
L*

There are no rules, there are no thumbs..
Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1211376]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (7)
As of 2024-04-25 15:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found