in reply to Balancing braces without (??{})
I'm fond of:
or evensub isBalanced { my $text= shift; my $brace= @_ ? shift : "{}"; my $start= substr( $brace, 0, length($brace)/2 ); my $end= substr( $brace, length($brace)/2 ); 0 while $text =~ s/\Q$start\E[^\Q$brace\E]*\Q$end\E//g; return $text !~ /[\Q$brace\E]/; }
modifying these to allow doing something with the matches is left as an exercise (as is testing). (: - tye (but my friends call me "Tye")sub notBalanced { my $brace= 1 < @_ ? $_[1] : "{}"; my $start= substr( $brace, 0, length($brace)/2 ); my $end= substr( $brace, length($brace)/2 ); my $depth= 0; for( split /[^\Q$brace\E]*/, $_[0] ) { if( index($start,$_) ) { $depth++; } elsif( index($end,$_) ) { return -1 if --$depth < 0; } } return $depth; }
|
|---|