几个月前我做了类似的事情,并认为这可能符合您正在寻找的内容......
c:\Perl>perl StackOverflow.pl
SomeValue
AND
-operator1
--operator2
---x
---a
--operator3
---y
---b
-operator4
--t
c:\Perl>
如果是这样,这是代码(如下)。这有点乱,但应该足以让你开始。
#!c:/perl/bin/perl.exe
my $SourceString="SomeValue AND (operator1(operator2(x,a),operator3(y,b)),operator4(t))";
my $NodeIndex=0;
my $IndexString="-";
print ProcessString($SourceString, $NodeIndex);
exit;
#----- subs go here -----
sub ProcessString {
my $TargetString=shift||return undef;
my $NodeIndex=shift;
my $ReturnString="";
#are we starting with a paren or comma?
if($TargetString=~m/^([\(\)\, ])/) {
#yep, delete the char and pass it through again for further processing
if($1 eq " ") {$ReturnString.=ProcessString(substr($TargetString, index($TargetString, $1)+1), $NodeIndex);}
elsif($1 eq ",") {$ReturnString.=ProcessString(substr($TargetString, index($TargetString, $1)+1), $NodeIndex);}
elsif($1 eq "(") {$ReturnString.=ProcessString(substr($TargetString, index($TargetString, $1)+1), ++$NodeIndex);}
elsif($1 eq ")") {$ReturnString.=ProcessString(substr($TargetString, index($TargetString, $1)+1), --$NodeIndex);}
} else {
#nope, must be a keyword or the end
if($TargetString=~m/([\(\)\, ])/) {
my $KeywordString=substr($TargetString, 0, index($TargetString, $1));
$ReturnString.=$IndexString x $NodeIndex;
$ReturnString.=$KeywordString."\n";
$ReturnString.=ProcessString(substr($TargetString, index($TargetString, $1)), $NodeIndex);
} else {
#we should never be here
} #end keyword check if
} #end if
#send the string back
return $ReturnString;
} #end sub
__END__