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

Hi, monks,
I'd like to write my own parser in Perl. How to do that? It should work for such script files:
#!parser_name some_command arguments yet_another_command
I prefer to avoid using of extra modules.

Replies are listed 'Best First'.
Re: Writing a parser
by kyle (Abbot) on Jan 29, 2008 at 20:05 UTC
Re: Writing a parser
by apl (Monsignor) on Jan 29, 2008 at 19:37 UTC
    You have a lot of work ahead of you. The very first thing you should do (after considering what you want the parser to produce, as moritz asked) is to develop the Backus-Naur Form you wish to parse.

    If you don't know what BNF is, you should ask yourself why you wish to develop a parser.

Re: Writing a parser
by moritz (Cardinal) on Jan 29, 2008 at 19:14 UTC
    It looks like you can just iterate over the lines, and check with regexes if the line starts with #, and split at whitespaces.

    But you have to be a bit more specific about the syntax, and what you want the parser to do with it (generate a parse tree? or an abstract syntax tree? Or execute it straight away?)

      Just based on what you are telling us, I would second this approach. I've written the following code many times:

      while (<FH>) { s/#.*$//; my @args = split(' ', $_); next unless @args; ... process command ... }

      If, however, you have any recursive syntactical elements (like begin/end grouping symbols which need to be matched), a proper parser written with Parser::RecDescent is probably in order.

A reply falls below the community's threshold of quality. You may see it by logging in.