True, PDA's are the proper tool for balancing parenthesis. But it helps if it works... Your PDA would match "))((" perfectly find. Most wouldn't consider that balanced...
sub balanced
{
my $string = shift;
my $stack = 0;
@string = split //, $string;
for (@string) {
last if $stack < 0;
$stack++ if /[(]/;
$stack-- if /[)]/;
}
return $stack ? 0 : 1;
}
or, without using split and //:
sub balanced
{
my $string = shift;
my $stack = 0;
for my $i (0..length($string)-1) {
last if $stack < 0;
$stack++ if substr($string,$i,1) eq '(';
$stack-- if substr($string,$i,1) eq ')';
}
return $stack ?0 : 1;
}