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

I've been trying to press the limits of s/// and regexs. Is there a way to convert a switch(.)-{case .:-default:} statement to a if(.){-} else if(.) {-} else {-} even with nesting through a/some s/// & regex expressions? In this language the 'default:' clause is required which makes it a bit easier. I've gotten a few examples to work but the nesting is throwing things off.

For example:

switch(trap_generic) { case 1: do stuff more stuff switch (varbind1) { case 'abc': print stuff case 'def': case 'g': do stuff default: # do nothing } case 2: still more stuff default: }
Any takers?

Replies are listed 'Best First'.
Re: S/// for Switch-case-default to if-if else-else conversion
by pc88mxer (Vicar) on Jul 07, 2008 at 03:18 UTC
    Recursive parsing is always troublesome with regular expressions. Since your code looks well-formatted, I would use a line-based approach which will make it a lot easier to "whip-it-up" (i.e. debug, develop, modify.)

    btw, what language is this for? - I have a feeling the language you are parsing is not perl. If it is, just use perl 5.10 which has given...when.

      It is Netcool rules file which is a proprietory glorified massive if then else statement with variable, field, and property assignments.
        Then you should show us what you want to convert it to. There are a lot of implementation details to consider. For instance, will you need to create an intermediate variable for the switch value, and if so, how do you do that? Also, how do you test for equality in Netcool, and is there a difference between string equality and number equality?
Re: S/// for Switch-case-default to if-if else-else conversion
by ysth (Canon) on Jul 07, 2008 at 03:48 UTC
    An easy way out is to not explicitly handle nesting, but do a 1 while s/.../.../ loop till all the levels are dealt with.
Re: S/// for Switch-case-default to if-if else-else conversion
by jethro (Monsignor) on Jul 07, 2008 at 12:23 UTC
    Have you considered using Parse::RecDescent? Brings some structure to the parsing job.