Do you know where your variables are? | |
PerlMonks |
Re: How to parse a limited grammarby TedYoung (Deacon) |
on Jan 10, 2008 at 16:35 UTC ( [id://661647]=note: print w/replies, xml ) | Need Help?? |
Well, if you are confident that the users of your software are trustworthy, you could simply apply one or more s///'s to the value and eval it:
This gives you tremendous power with a minimum amount of work. Though, if you don't completely trust your users, it may give you too much power. You could limit that with Safe, but that has been shown not to be a complete sandbox (it makes it much harder for the user to inadvertently screw up things, but if they have their heart set on it, they can exploit certain flaws). HOP::Parser is great but very, very slow. You only need it if you are parsing streams. Here you have very short strings and, if the above solution won't work for you, you can use traditional lexing semantics to build up a list of tokens. Your grammar is probably simple enough to simply iterator over those tokens and generate valid perl to be eval'ed (or derive the value as you go).
Note that if you want proper nesting of () in method calls, you will need to use a better regex. Continue to add tokenizers for operators (|, &) etc. When done, just iterate over the list of tokens and generate either the value or if necessary generate trusted perl code and eval it. update:
update 2: If you choose either eval option above, you can expose variables to your value code like this:
This exposes variables to your value code without the need of globals and namespaces. Ted Young It is almost impossible for me to read contemporary mathematicians who, instead of saying "Petya washed his hands," write simply: "There is a t1 < 0 such that the image of t1 under the natural mapping t1 -> Petya(t1) belongs to the set of dirty hands, and a t2, t1 < t2 <= 0, such that the image of t2 under the above-mentioned mapping belongs to the complement of the set defined in the preceding sentence."
In Section
Seekers of Perl Wisdom
|
|