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
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: a word of warning about /$pattern/
by demerphq (Chancellor) on Dec 02, 2003 at 16:39 UTC | |
Re: a word of warning about /$pattern/
by diotalevi (Canon) on Dec 02, 2003 at 14:48 UTC | |
Re: a word of warning about /$pattern/
by Theo (Priest) on Dec 02, 2003 at 15:42 UTC | |
by dada (Chaplain) on Dec 02, 2003 at 16:05 UTC | |
by Theo (Priest) on Dec 02, 2003 at 17:17 UTC | |
Re: a word of warning about /$pattern/
by vacant (Pilgrim) on Dec 03, 2003 at 04:49 UTC | |
by ambrus (Abbot) on Dec 03, 2003 at 13:07 UTC | |
by demerphq (Chancellor) on Dec 06, 2003 at 11:15 UTC | |
by Aristotle (Chancellor) on Dec 07, 2003 at 09:43 UTC | |
by demerphq (Chancellor) on Dec 07, 2003 at 18:06 UTC | |
by Aristotle (Chancellor) on Dec 08, 2003 at 06:20 UTC | |
Re: a word of warning about /$pattern/
by hardburn (Abbot) on Dec 02, 2003 at 14:48 UTC | |
by zby (Vicar) on Dec 02, 2003 at 15:43 UTC | |
Re: a word of warning about /$pattern/
by Roger (Parson) on Dec 03, 2003 at 02:51 UTC |