Do you know where your variables are? | |
PerlMonks |
Re: Arrays and grep problemsby Kenosis (Priest) |
on Jan 24, 2014 at 19:43 UTC ( [id://1071986]=note: print w/replies, xml ) | Need Help?? |
You've been given excellent tips for improving your script. In an earlier response to you, Laurent_R suggested two methods for accomplishing your task. The following addresses one of those, as I think it's a good option. When you're looking for keywords in each line, you're effectively joining them with OR. For example: print the current file's line if it contains 'Hello' OR 'world' OR 'today'. In a regex, the OR function is accomplished using alternation:
The (?:) notation forms a non-capturing group. It's not strictly necessary here, but is used to just cluster the set of disjuncts. There are a few issues with the above regex which need to be addressed. One is that, as it is, it's case sensitive. That is, 'today' would match but 'Today' wouldn't. To create a case-insensitive match, use the i modifier:
The next issue is that the above regex would match 'worldly'--and you may not want in-string matching. To prevent in-string matching, you need to match words enclosed by word boundaries:
The last item to consider comes when you may want to match a phrase like 'Mr. Smith'. The problem is that the period in the string is a regex meta-character used to match one character. This period, and other meta-characters, must be escaped for a literal match: 'Mr\. Smith'. Give the above considerations, the script below implements them:
The "\\b\Q$_\E\\b" notation first quotes all meta-characters in the word (\Q...\E) and the \\b means word boundary. There are two "\", because the first escapes the second, leaving the literal "\b" in the string. Print both $words and $regex to see what's constructed. Usage: perl script.pl [>outFile] The last, optional parameter directs output to a file. Hope this helps!
In Section
Seekers of Perl Wisdom
|
|