I need to find matching pairs of parenthesis and call a sub that expands each function. My first attempt was to use recursion and a regex with greedy search. This works for example 1, but fails for example 2 because the regex does not find the matching parenthesis:Example 1: A(B(2)) Example 2: A(B(2)+C(D()))
Any help is greatly appreciated. Thanks!#!/usr/bin/perl -wT # example 1 my $text = "A(B(2))"; $text = doFunc( "MAIN", $text ); print "Example 1: $text\n"; # example 2 $text = "A(B(2)+C(D()))"; $text = doFunc( "MAIN", $text ); # this fails! print "Example 2: $text\n"; sub doFunc { my( $theFunc, $theParam ) = @_; # FIXME: greedy match fails with: 'TT(TT()+TT(TT()))' $theParam =~ s/([A-Z]+)\((.*)\)/&doFunc($1,$2)/geo; my $result = ""; if( $theFunc eq "MAIN" ) { $result = $theParam; } else { # dummy switch here for demonstration # this would be an elsif for each function $result = "func $theFunc returns <$theParam>"; } return $result; }
In reply to How to find matching pairs by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |