in reply to Re: Using qw to check for balanced parentheses (oops)
in thread Using qw to check for balanced parentheses

sub balanced { local $_ = shift; s/[^()]//g; eval "qw($_)"; ! $@ }

Replies are listed 'Best First'.
Re^3: Using qw to check for balanced parentheses (oops)
by ikegami (Patriarch) on Sep 16, 2011 at 19:51 UTC

    Simplified return value and shortened code by avoiding needless use of $_:

    sub balanced { (my $s = shift) =~ s/[^()]//g; eval "qw($s); 1" }

    Or in 5.14+:

    sub balanced { my $s = shift =~ s/[^()]//rg; eval "qw($s); 1" }

      I may be mistaken, but this does not detect a case like

      "}a{"

      , or does it?

      how about

      sub balanced { (my $s = shift) =~ s/[^()]//g; while ( $s =~s /\(\)// ){}; return $s ? 0 : 1; }
      It does not use qr and is slower, I would think, but reports '}{' as incorrect
Re^3: Using qw to check for balanced parentheses (oop)
by tye (Sage) on Sep 16, 2011 at 19:42 UTC

    Very nice!

    - tye