some days ago I was playing with an "advanced search"-like form, one of these where you can fill one or more search fields. something like:
of course, some of the fields could be blank. the searching code, reduced to its minimum, was something like:# example of form: # Name: __________ # Address: __________ # Telephone: __________ # etc. # [Search]
the match mysteriously failed when filling just the "Name" field, and I was puzzled for a few hours before finding out what was wrong.if( $name =~ /\Q$pattern_name\E/i and $address =~ /\Q$pattern_address\E/i and $telephone =~ /\Q$pattern_telephone\E/i) { print "matched\n"; }
the bug is really subtle indeed, and if you can spot it at a first glance, ++ to you.
so, if I put, for example "da" in the "Name" field, my if statement tries to match name, address AND telephone from my database with "da". and this obviously fails. even putting debug statements outside the if, just to check what I thought was matched (eg. print the pattern, print the result of $data =~ /pattern/) didn't help, because it's the order of the matches that screw things up.
I ended up changing my code to something like:
(I know, I could I've just used index instead of a regexp in this case, but the principle still applies).if( (not $pattern_name or $name =~ /\Q$pattern_name\E/i) and (not $pattern_address or $address =~ /\Q$pattern_address\E/i) and (not $pattern_telephone or $telephone =~ /\Q$pattern_telephone\E/i +) ) { print "matched\n"; }
and what I've learned is: something like /$pattern/ (I mean, just a variable inside a regexp and nothing else) is probably a bad idea, unless you're really, really sure that $pattern will actually contain something.
Aldo
King of Laziness, Wizard of Impatience, Lord of Hubris