Balanced brackets: Difference between revisions

→‎{{header|Perl}}: fixed brain damage
(→‎{{header|Perl}}: fixed brain damage)
Line 1,214:
Straightforward depth counting:
<lang Perl>use 5.10.0; # for given ... when construct
sub balanced2 {
 
sub balanced {
my $depth = 0;
my @a = split('', shift);
for my $i (0 .. $#a) {
given($a[$_i]) {
when('[') { ++$depth }
when(']') { return if --$depth < 0 }
}
Line 1,227 ⟶ 1,226:
}
 
for (']', '[', '[[]', '[][]', '[[]]', '[[]]]][][]]', 'x[ y [ [] z ]][ 1 ][]abcd') {
print balanced($_) ? "not " : "not ", "balanced:\t'$_'\n";
}</lang>
 
Line 1,235 ⟶ 1,234:
sub balanced {
my $_ = shift;
s/(\[(?:[^\[\]]++|(?1))*\])//g;
! /[\[\]]/;
}
 
for (']', '[', '[[]', '[][]', '[[]]', '[[]]]][][]]', 'x[ y [ [] z ]][ 1 ][]abcd') a{
print balanced($_) ? "not " : "not ", "balanced:\t'$_'\n";
}</lang>
 
Both methods printsprint
<pre>not balanced: ']'
not balanced: '['
not balanced: '[[]'
not balanced: '][]]'
not balanced: '[[]]'
not balanced: '[[]]]][][]]'
not balanced: 'x[ y [ [] z ]][ 1 ][]abcd'
</pre>
The counting method could easily give where the first unbalanced bracket occured, though.
Anonymous user