sub balanced { my( $str )= @_; my $d= 0; while( $str =~ m(([(])|([)]))g ) { if( $1 ) { $d++; } elsif( --$d < 0 ) { return 0; } } return 0 == $d; }