Anonymous user
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 {
my $depth = 0;
my @a = split('', shift);
for my $i (0 .. $#a) {
given($a[$
when('[') { ++$depth }
when(']') { return if --$depth < 0 }
}
Line 1,227 ⟶ 1,226:
}
for (']', '[', '[[]', '
print balanced($_) ? "
}</lang>
Line 1,235 ⟶ 1,234:
sub balanced {
my $_ = shift;
s/(\[(?:[^\[\]]++|(?1))*\])//g;
! /[\[\]]/;
}
for (']', '[', '[[]', '
print balanced($_) ? "
}</lang>
Both methods
<pre>not balanced:
not balanced:
not balanced:
not balanced:
not balanced:
</pre>
The counting method could easily give where the first unbalanced bracket occured, though.
|