Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

Match nested parens of arbitrary depth in 56 characters

by dchetlin (Friar)
on Oct 29, 2000 at 02:07 UTC ( #38942=snippet: print w/replies, xml ) Need Help??
Description: This code is neither robust nor efficient nor general. But it's short and fun. Making it any of those things is not difficult, but it won't be do-able in 56 chars.

It doesn't deal with escaped or quoted parens -- i.e. they are treated like any other. It doesn't deal with nulls in the input very well, to make it do that would cost 3 extra chars. It doesn't let you know where you're unbalanced, but simply prints `1' if the input is balanced and prints nothing if it's not. Oh, and it requires 5.6.0 or better.

Give it a filename to check for balancing on the command line, or run it as shown below exactly and give it text to check on standard input.


perl -n0e'$r=qr/(?>[^()]*)|\((??{$r})+\)/;print/^$r*$/'
Replies are listed 'Best First'.
40 characters, works even in Perl4
by I0 (Priest) on Dec 18, 2000 at 11:16 UTC
    perl -p0e 'tr/()//cd;eval{/$_/};$_=!$@'
      perl -p0e'y/()//cd;eval{/$_/};$_=!$@'
Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://38942]
Discipulus never noticed there was subtitles... can I call them with &subtitle or is too much perl 4?
[LanX]: YT=youtube
[Discipulus]: ;=) yes i'm not SO dumb
[LanX]: SO=StackOverflow
[Discipulus]: :=(
[perldigious]: I watched some video on YT awhile back with auto-subtitle on and the speaker had a very thick cockney sort of English accent... hillarity ensued in the subtitles.
[Discipulus]: IHAA=I hate acronyms anyway

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (8)
As of 2017-06-23 16:39 GMT
Find Nodes?
    Voting Booth?
    How many monitors do you use while coding?

    Results (552 votes). Check out past polls.