Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: How do you use a variable value within a regular expression pattern properly? (updated)

by haukex (Archbishop)
on Sep 11, 2017 at 11:43 UTC ( [id://1199084]=note: print w/replies, xml ) Need Help??


in reply to How do you use a variable value within a regular expression pattern properly?

As an alternative to what 1nickt showed, there's also the /x modifier that allows you to insert whitespace in your regex, which also improves readability:

if( $string=~/ ^ $myvar REC: (.*) /x )

Also, Mind the meta!, that means if your $myvar contains any characters like the dot (.) and you don't want these to be interpreted as regex special characters, or any whitespace in the variable to be ignored under /x, then you need to wrap your string in \Q...\E (see also quotemeta):

if( $string=~/ ^ \Q$myvar\E REC: (.*) /x )

Update: Added links to docs. Also added bit about whitespace in the variable under /x.

Update 2: Just to be clear, I recommend you always use \Q...\E, even if you don't use /x, unless you specifically want regex metacharacters in $myvar to be treated as such and it comes from a trusted source! That is, if($string=~/^\Q$myvar\EREC:(.*)/)

  • Comment on Re: How do you use a variable value within a regular expression pattern properly? (updated)
  • Select or Download Code

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (5)
As of 2024-04-23 12:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found