Back to your problem - since perl's grammar is recursive: (... ( sub expression ) ...) you have to keep track of parenthesis balancing. You need to use some kind of stack structure (an explicit one or the call stack) to nibble paren tokens, and construct nested subexpressions. Once you can build that much you need to reserialize your structures back. Since you are only going two levels deep, this will be a problem soon.

You can use regexes to find tokens, but the notion of state must be maintained, and this is not taken into account in your code.

Your subroutine regex is the problem there, btw. It doesn't match a closing paren, so the collected string ends in "WebGUIProfile", and stops there. A hard coded paren for the method call is printed, and that's where it ends.

Without looking at your actual problem, and recognizing that you're doing this as an exercise, can I nonetheless recommend Perl::Tidy to reformat your code, leaving you free for other more useful things? Parsing Perl is notoriously difficult, most say impossible.