Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: Idiomatic Perl? -- eval qr/ /

by Discipulus (Abbot)
on Mar 20, 2018 at 20:37 UTC ( #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
Node Status?
node history
Node Type: note [id://1211376]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (3)
As of 2021-04-10 20:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?