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

Hey, this is a question for a first time perl user, so please excuse this :) I have to write a database system that reads in a file and places an address book into an array of hashes. Done. Then I have to take a query string from standard in that could look like

Name[James]

or

Name[James] && Phone[734]

or

!((Name[Mike]||(Name[James]))&&!Phone[313])

Please notice that I cannot use spaces as a way of breaking the string up. I am to read NOTs, ANDs, ORs, parens, and queries into seperate arrays in the order they apppear in the query and then do a shift/reduce pattern on them to search the database. However, I cannot even parse the string. Some people in class used a search and replace; another used grep and split in one line to do so. I cannot get any of them. I would think that grep and split would work best, but I can't figure out how to do any of them. If someone could help me here, or even go so far as how to perhaps use a series of recursive subroutines to get results, I would appreciate it. Thanks!

-james

p.s. - ok, I noticed that the names are now underlined - they are supposed to be surrounded by square brackets... my apologies, I'm not sure what's happening lol

Replies are listed 'Best First'.
Re: Perl database system
by kvale (Monsignor) on Apr 26, 2004 at 22:07 UTC
    Sounds like homework :) In a complex project like this, it is best to break it down into managable steps. The general steps to take are
    • Lexing: decide what the tokens are
    • Create a grammar for your search expressions, using tokens as your terminal elements
    • Code up a parser - recursive descent would work here
    • Run the expression through the parser, creating a parse tree
    • Walk the parse tree, executing search code
    I can't make sense of the detailed requirements you state, but depending on what they are, you might be able to take some shortcuts. For instance, if the column names and corresponding values are always alphanumeric, these would be easy to distingush from the logical and grouping tokens of a search expression. Also, your task is simple enough that the parsing and executuion steps can be combined (look up syntax-directed translation in your book).

    -Mark

Re: Perl database system
by Jaap (Curate) on Apr 26, 2004 at 22:10 UTC
    If you have a subroutine that can check a Func[value] then you can eval the ANDs OR's etc as if they are Perl operators.

    edit: used a [ for [
Re: Perl database system
by borisz (Canon) on Apr 26, 2004 at 23:32 UTC