Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
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; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: How to find matching pairs
by ajwans (Scribe) on Mar 12, 2002 at 02:18 UTC | |
by Anonymous Monk on Mar 12, 2002 at 05:31 UTC | |
|
Re: How to find matching pairs
by rnahi (Curate) on Mar 12, 2002 at 07:31 UTC | |
|
Re: How to find matching pairs
by I0 (Priest) on Mar 12, 2002 at 09:47 UTC | |
|
Re: How to find matching pairs
by Anonymous Monk on Mar 12, 2002 at 05:38 UTC | |
by IlyaM (Parson) on Mar 12, 2002 at 10:05 UTC | |
|
Re: How to find matching pairs - thanks!
by Anonymous Monk on Mar 12, 2002 at 22:07 UTC |