powerhouse has asked for the wisdom of the Perl Monks concerning the following question:

I have a search tool, that I'm trying to allow mulitple search "keywords" to be entered. I'm having them put spaces between each keyword. They can also put in "item numbers", to search for seperated by spaces. So, my question is this. What is the best way to split each keyword?
($key1,$search_keys) = split / /, $search_keys, 2; # OR ($key1,$search_keys) = split /\s/, $search_keys, 2;
Or is there even a better way?

thx,
Richard

Replies are listed 'Best First'.
Re: Split question...
by dws (Chancellor) on Apr 21, 2003 at 17:39 UTC
    What is the best way to split each keyword?

    The docs on split (in perlfunc) mention a special-case for dealing with multiple spaces.

    When you do

    ($key1,$search_keys) = split / /, $search_keys, 2;
    is it your plan to do this in a loop, pulling of next search term each time through? I would think it would be easier to just do
    @keys = split / /, $search_keys;
    Or is there something about item numbers that makes it easier to do it your way?

      Well, here is how I'm doing it....
      $search_keys = $in{keywords}; while ($search_keys) { ($key1,$search_keys) = split /\s/, $search_keys, 2; if (Check_Database($key1)) { # checks if item num $page_content .= Get_Search_Results($key1,"item_num"); } else { $search_engine .= Get_Search_Results($key1,"keyword"); } }

      That is not working though. I don't know why, I guess I'll just play with it, while taking Mad Hatters advice of /\s+/ in the split, just in case they put more spaces then 1.

      Thank you for your advice.

      thx,
      Richard
        Wouldn't it be easier to do something like
        @search_keys = split /\s+/, $in{keywords}; foreach $key (@search_keys) { if (Check_Database($key)) { # checks if item num $page_content .= Get_Search_Results($key,"item_num"); } else { $search_engine .= Get_Search_Results($key,"keyword"); } }
Re: Split question...
by The Mad Hatter (Priest) on Apr 21, 2003 at 17:39 UTC
    You'll probably want to allow for more than one space between keywords to account for sloppy data entry.
    @keywords = split /\s+/, $search_keys;
Re: Split question...
by Your Mother (Archbishop) on Apr 21, 2003 at 21:41 UTC
    You might take it further too, depending on what you allow to search for. If you index (or raw search) on everything this doesn't matter, but many searches index on wordlike items. If you're doing that, something like this might be good:

    ...split /[^-\w']+/, $search_keys, 2;

    So you only search for numbers and text (more or less). But that will slurp up extra stuff on the end, possibly corrupting the second element returned.

    Maybe something like this?

    my @keepers; for my $q ( split /[^-\w']+/, $search_keys ) { push @keepers, $q; last if @keepers == 2; }

    The one thing you can count on with UI is that the U will not I as you expect him/her to.