in reply to How to find matching pairs
-- Peter at Thoeny.com - http://TWiki.org/#!/usr/bin/perl -wT $escToken = "\263"; parseText( "Example 1: A(B(2))" ); parseText( "Example 2: A(B(2)+C(D()))" ); sub parseText { my( $theText ) = @_; my $level = 0; print "== $theText\n"; # add nesting level to parenthesis, # e.g. "A(B())" gets "A-esc-1(B-esc-2(-esc-2)-esc-1)" $theText =~ s/([\(\)])/addNestingLevel($1, \$level)/geo; $theText = doFunc( "MAIN", $theText ); # clean up unbalanced mess $theText =~ s/$escToken\-*[0-9]+([\(\)])/$1/go; print "-> $theText\n"; return $theText; } sub addNestingLevel { my( $theParen, $theLevelRef ) = @_; my $result = ""; if( $theParen eq "(" ) { $$theLevelRef++; $result = "$escToken$$theLevelRef$theParen"; } else { $result = "$escToken$$theLevelRef$theParen"; $$theLevelRef--; } return $result; } sub doFunc { my( $theFunc, $theParam ) = @_; $theParam =~ s/([A-Z]+)$escToken([0-9]+)\((.*?)$escToken\2\)/&doFunc +($1,$3)/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; }
|
|---|