sub peeln { local $_ = shift; my $n = shift; my($o, $c) = (tr[(][], tr[)][]); warn 'Unbalanced parens' unless $o == $c; $n = $c if $n == -1 or $n > $c; m[^ (?: .*? \( .*?){$n} (.+) (?: .*? \) .*?){$n} $]x; $1; } my @tests = ( 'hello(what(is(this(all(about)))))', 'hello(what(is(this(all(about))))))', 'hello((what(is(this(all(about)))))', 'A(B(c) D(e) f(g(h(i))))', ); for my $test ( @tests ) { print "$test : $_ : ", peeln( $test, $_ ) for -1 .. 5; } __END__ P:\>270595 hello(what(is(this(all(about))))) : -1 : about hello(what(is(this(all(about))))) : 0 : hello(what(is(this(all(about))))) hello(what(is(this(all(about))))) : 1 : what(is(this(all(about)))) hello(what(is(this(all(about))))) : 2 : is(this(all(about))) hello(what(is(this(all(about))))) : 3 : this(all(about)) hello(what(is(this(all(about))))) : 4 : all(about) hello(what(is(this(all(about))))) : 5 : about Unbalanced parens at P:\270595.pl8 line 28. Use of uninitialized value in print at P:\270595.pl8 line 42. hello(what(is(this(all(about)))))) : -1 : Unbalanced parens at P:\270595.pl8 line 28. hello(what(is(this(all(about)))))) : 0 : hello(what(is(this(all(about)))))) Unbalanced parens at P:\270595.pl8 line 28. hello(what(is(this(all(about)))))) : 1 : what(is(this(all(about))))) Unbalanced parens at P:\270595.pl8 line 28. hello(what(is(this(all(about)))))) : 2 : is(this(all(about)))) Unbalanced parens at P:\270595.pl8 line 28. hello(what(is(this(all(about)))))) : 3 : this(all(about))) Unbalanced parens at P:\270595.pl8 line 28. hello(what(is(this(all(about)))))) : 4 : all(about)) Unbalanced parens at P:\270595.pl8 line 28. hello(what(is(this(all(about)))))) : 5 : about) Unbalanced parens at P:\270595.pl8 line 28. hello((what(is(this(all(about))))) : -1 : all(about Unbalanced parens at P:\270595.pl8 line 28. hello((what(is(this(all(about))))) : 0 : hello((what(is(this(all(about))))) Unbalanced parens at P:\270595.pl8 line 28. hello((what(is(this(all(about))))) : 1 : (what(is(this(all(about)))) Unbalanced parens at P:\270595.pl8 line 28. hello((what(is(this(all(about))))) : 2 : what(is(this(all(about))) Unbalanced parens at P:\270595.pl8 line 28. hello((what(is(this(all(about))))) : 3 : is(this(all(about)) Unbalanced parens at P:\270595.pl8 line 28. hello((what(is(this(all(about))))) : 4 : this(all(about) Unbalanced parens at P:\270595.pl8 line 28. hello((what(is(this(all(about))))) : 5 : all(about Use of uninitialized value in print at P:\270595.pl8 line 42. A(B(c) D(e) f(g(h(i)))) : -1 : A(B(c) D(e) f(g(h(i)))) : 0 : A(B(c) D(e) f(g(h(i)))) A(B(c) D(e) f(g(h(i)))) : 1 : B(c) D(e) f(g(h(i))) A(B(c) D(e) f(g(h(i)))) : 2 : c) D(e) f(g(h(i)) A(B(c) D(e) f(g(h(i)))) : 3 : e) f(g(h(i) A(B(c) D(e) f(g(h(i)))) : 4 : g(h(i Use of uninitialized value in print at P:\270595.pl8 line 42. A(B(c) D(e) f(g(h(i)))) : 5 :