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

Hi people, I was looking into the idea of taking for example a verilog or c or C++ file and somehow parse it with perl and storage them in a hash structure. Then maybe i can edit those hash structures and call some function to rebuild the file back from the alter hash. Got any ideas on how I can start?

Replies are listed 'Best First'.
Re: looking Generic File Parser script?
by tachyon (Chancellor) on Nov 25, 2004 at 23:44 UTC

    As noted you want a recursive descent parser like Parse::RecDescent. A parser needs a grammar. Fortunately the Inline:: modules all use PRD to parse the language code so you have a good start on a C grammar in Inline::C::ParseRecDescent and a C++ grammar in Inline::CPP::Grammar

    You do not want to generate a HASH as this is unordered, whereas code is definitively ordered. You want what PRD gives you which is an array of array refs to whatever depth. You may find the thread Parse:RecDescent grammar help useful.

    cheers

    tachyon

Re: looking Generic File Parser script?
by fergal (Chaplain) on Nov 25, 2004 at 23:24 UTC
    Well Parse::RecDescent is one way of doing things. It's quite easy to write a parser with this and you can find plenty of info about it on the net. You can find 2 C grammars as part of the Inline module, one is written with PRD above and the other is done with regexs it seems.
Re: looking Generic File Parser script?
by toma (Vicar) on Nov 27, 2004 at 05:26 UTC
    To parse Verilog, you can use Hardware::Verilog::Parser. I used this parser on a large Verilog library. It worked, but it was a bit slow for my purposes.

    Maybe someone else knows of a C or C++ parser that is similar. Parsers are not generic because they depend on the grammar of the language being parsed.

    If you store the code in a hash and want to re-assemble it, you'll need some way to get the code to come out in order, since an ordinary perl hash doesn't preserve order.

    Instead of an ordinary hash, use one of perl's object-oriented data structure modules. The best module to choose for your task depends on a lot of details, so please describe your problem in more detail to get better advice on this.

    It should work perfectly the first time! - toma