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

Hello:

I have a data column (lastname) in a MySQL database. I'm using DBI and going to sort ORDER BY the last name so it is in alphabetical order. I want a A-K, and a L-Z list. How would I use regex or index to split the array up?

Thank you,

Anthony

Replies are listed 'Best First'.
Re: Regex or Index
by pg (Canon) on Nov 20, 2002 at 23:24 UTC
    Actually you can do it in your SQL statement, just add this in your SELECT:
    LastName LIKE '[A-K]*' for one case, and LastName LIKE '[L-Z]*' for the other case.
      Hello

      Thanks for reply. I tried using your advice, but no luck. Im sort of a MySQL newbie and confused on how I would put that statement with mine.

      $sql = "SELECT * FROM mailtodo where date = '$INPUT{'date'}' AND lastn +ame LIKE '[A-K]*'";
      The statement above returns no results, but should. I need the where date syntax because I'm also sorting the data by date. Thanks,

      Anthony

Re: Regex or Index
by graff (Chancellor) on Nov 21, 2002 at 02:00 UTC
    On the other hand, if you did just one query into an array, you could use grep on the array to create two subset arrays:
    @A_K = grep /^[A-K]/, @query_results; @L_Z = grep /^[L-Z]/, @query_results;
    On the the third hand, if you were using a DBI function that returns one row per iteration, you could split the set within the fetch loop, like this:
    my @A_K; my @L_Z; my $aref = \@A_K; while ( my $row = $dbh->fetchrow_arrayref ) { $aref = \@L_Z if ( $$row[$last_name_col] =~ /^L/ ); push @$aref, [ @$row ]; }

    update: Note that the latter both methods assume that you're still using the "ORDER BY" clause in your SQL; in the former, the sequence is preserved in both subsets; in the latter, once you hit a name that starts with "L", you switch to the second array for collecting all remaining rows.

      The latter solution itches me because you're doing the test for each row, even after you switched. Note it will also fail if there's no name starting with an L in the output.

      I'd do something like:

      while (my $row = $dbh -> fetchrow_arrayref) { if ($row -> [$last_name_col] =~ /^[L-Z]/) { push @L_Z => $row; while (my $row = $dbh -> fetch_arrayref) { push @L_Z => $row; } last; } push @A_K => $row; }
Re: Regex or Index
by amarceluk (Beadle) on Nov 21, 2002 at 14:32 UTC
    A caveat to append to the answers here, based on much work with biographical dictionaries: don't assume last names always begin with capital letters (unless your database has all-caps fields). I'd recommend making your search case-insensitive, in case there are names like de Vries or al-Rashid.

    __________
    "Abby-somebody. Abby-normal."
    Young Frankenstein