http://www.perlmonks.org?node_id=483039


in reply to Pattern Matching Confusion

I'd first recommend using some XML parser. Check CPAN for one that will easily handle the XML structure that you are looking at. Some are better than others for deep data structures, others are better at flatter data structures; some parse the entire document as a whole (loads the whole thing into memory), others parse it as you go. TMTOWTDI.

On a completely separate note, but attempting to pass on more general Perl wisdom, you have a couple of lines of code that literally make me cringe.

while ($record = <INPUTFILE>) { $_ = $record; if (/$searchString/g) { print $record; $matchesFound = $matchesFound + 1; } }
Here, you explicitly assign the next line in your file to a variable, then assign that variable to $_ (the default variable) so you can do a pattern match on the default variable and then print your explict variable. You only need one of these two variables. Since you do not need to do anything specific with $record, you could just as easily do this:
while (<INPUTFILE>) { ++$matchesFound && print if (/$searchString/); }
This will automatically assign to $_. print() will default to $_. You will increment $matchesFound and print $_ if $_ matches you pattern. Also note that you do not need the /g modifier since you do not need to find all matches, just any match.

Another way to do this (TMTOWTDI) is to assign the line to a real variable (as you do) but then use the =~ operator to pattern match against that variable:

while ($record = <INPUTFILE>) { if ($record =~ /$searchString/) { print $record; $matchesFound++; } }

Ivan Heffner
Sr. Software Engineer, DAS Lead
WhitePages.com, Inc.