Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

I just want to point out the potential bug that is almost always lurking around uses of split /\s+/. If there is leading whitespace in the string, that code will give you a null leading element in the return list. In the case of arturo's search routine above, if the search term passed in happens to contain a leading space (for whatever reason), then the pattern constructed will look like /|term1|term2|etc/ and will match on any string (and this bug might be difficult to spot -- even if you print out the pattern string you might not notice the leading | in the pattern).

So, the moral is, usually when you want to split on multiple whitespace you'll want to use the special case of just a string with a single space in it as the first argument to split(), ie: split " ", $terms;. (and split() with no arguments is just doing: split(" ",$_)).

A second point about your search subroutine is that you can use the construct the pattern with the case sensitive switch embedded in the pattern via (?i). You can also then use the qr// operator so that the regex does not have to be recompiled for each name passed through the grep block. So, I'd change that routine to:

sub search { my $terms = shift; my $pattern = join "|", split " ", $terms; my $case = $FORM{case} eq 'insensitive'?"(?i)":""; $pattern = qr/$case$pattern/; my @matches = grep { /$pattern/ } @names; return \@matches; }

In reply to don't get bit by split. by danger
in thread @arrys & Non exact searches. by akm2

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (5)
As of 2024-04-24 22:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found