Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Variables as pattern matching options 1

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
0
0
I am doing a search through text.
The search goes in the format of:
$text =~ /$pattern/i
to make it case insensitive.
What i really want is to make it case insensitive depending on a variable.
Now I know that I COULD do it by having if clauses at every search...
but there are a LOT of searches and that would make the script inefficient.
Therefore i have the line at the top saying:
$case = "i" if ($sensitive eq "no");
$case = "" if ($sensitive eq "yes");
And i want all of my search lines (and there are a LOT) to say:
$text =~ /$pattern/$case
however it interprets it as a non scalar and falls over.
In what format, if any, an i put the $case in order to make it search with
or without
i dependent on $case without having two lines of if... else at each search.

Thanks a lot guys
Gareth
Thermeon Europe Ltd
Gbjk@carsplus.co.uk
 
This trick depends a little on which version of perl you use. It works in the newest 5.6 stuff, and I know it dosen't work before 5.0, but in between is a grey area for me. Basically, you want to do a precompiled regular expression in your search with qr (man perl opt for more info). Assuming you have some command line option $opt_i to say case in/sensitive, it could look something like this:
Code:
$compiled_search =~ ($opt_i? qr/$pattern/i : qr/$pattern/);
#more code...
if ($text =~ $compiled_search){#do something}

Of course, your mileage may vary, but that's the jist of it. The magic to look for if you need to tweak that is qr.

Rajoidea
 
Another way to do this is to use embedded pattern-match operators (see man perlre). These work by adding a string with the pattern match parameters before the regular expression. For example (building on your code):
Code:
# $case will contain embedded pattern-match operator
$case = "(?i)" if ($sensitive eq "no");
$case = "" if ($sensitive eq "yes");

# use operator preceding regular expression
if ($text =~ /$case$pattern/) {
...
}
 
sackyhack's answer is the one I would use. That's pretty much the reason the for that extension.
Tracy Dryden
tracy@bydisn.com

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top