"be consistent" | |
PerlMonks |
Re: Seeking Advice: Writing a parserby jryan (Vicar) |
on Feb 08, 2002 at 05:07 UTC ( [id://144038]=note: print w/replies, xml ) | Need Help?? |
Something like this needs a recursive parser. Aside from suggesting Parse::RecDescent or the example in Japhy's book, I'll give a few suggestions on how I would approach this. First off, you are correct in storing it a tree-type data structure. However, don't use a normal hash; I recommend Tie::IxHash to keep an ordered hash since you will need to reorder later. Next, you will need to figure out a way of determining whether a term is top level, and separate those terms from each other. Simply splitting on /[+-]/ wont be enough; you'll need to inchworm through in order and determine context. Next, you'll have to separate those terms which are /[*\/]/, and mark those as separate parts of one term. Finally, you'll need to deal with leftovers, such as exponentiation, function calls, etc. Once you have the top level terms in the tree, you'll have descend into each node and repeat the process (here is where the recursion comes in.) You'll need to do it again, and again, and again, until everything is parsed to its lowest level. Finally, you'll have to work backwards from the bottom to perform the calculations. Not as easy as you thought, was it? That's why there is CPAN :)
In Section
Seekers of Perl Wisdom
|
|