in reply to Using qw to check for balanced parentheses

It doesn't appear to work?

$ perl -le' sub is_balanced { my $string = shift; eval("qw($string)"); return 0 if @$; return 1; } my $balanced = "(1 + 2 * (3 + (5/4) + 8) + 6)"; my $unbalanced1 = "(((1 + 2 * (3 + (5/4) + 8) + 6))"; my $unbalanced2 = "(((1 + 2 * (3 + (5/4) + 8) + 6))))"; printf("Is $balanced balanced? %s\n", is_balanced($balanced) ? "yes" : + "no"); printf("Is $unbalanced1 balanced? %s\n", is_balanced($unbalanced1) ? " +yes" : "no"); printf("Is $unbalanced2 balanced? %s\n", is_balanced($unbalanced2) ? " +yes" : "no"); ' Is (1 + 2 * (3 + (5/4) + 8) + 6) balanced? yes Is (((1 + 2 * (3 + (5/4) + 8) + 6)) balanced? yes Is (((1 + 2 * (3 + (5/4) + 8) + 6)))) balanced? yes

Replies are listed 'Best First'.
Re^2: Using qw to check for balanced parentheses
by Anonymous Monk on Feb 01, 2011 at 23:16 UTC
    typo @$; is not $@;

      Yes, that works a lot better.   :-)

      Of course, the subroutine could be reduced to just:

      sub is_balanced { eval "qw($_[0])" }

      And it will also work with qq as well as with qw.

      $ perl -le' sub is_balanced { eval qq($_[0]) } my $balanced = "(1 + 2 * (3 + (5/4) + 8) + 6)"; my $unbalanced1 = "(((1 + 2 * (3 + (5/4) + 8) + 6))"; my $unbalanced2 = "(((1 + 2 * (3 + (5/4) + 8) + 6))))"; print "Is $balanced balanced? ", is_balanced( $balanced ) ? "yes" : "n +o"; print "Is $unbalanced1 balanced? ", is_balanced( $unbalanced1 ) ? "yes +" : "no"; print "Is $unbalanced2 balanced? ", is_balanced( $unbalanced2 ) ? "yes +" : "no"; ' Is (1 + 2 * (3 + (5/4) + 8) + 6) balanced? yes Is (((1 + 2 * (3 + (5/4) + 8) + 6)) balanced? no Is (((1 + 2 * (3 + (5/4) + 8) + 6)))) balanced? no
        That won't handle "" hand "0", but that's easy to fix:
        sub is_balanced { eval "qw($_[0]); 1" }
        sub is_balanced2 { not    $_[0] =~ tr/)(//    % 2; }
      D'oh! Thanks, I'm too used to dereferencing arrays.
Re^2: Using qw to check for balanced parentheses
by Anonymous Monk on Oct 23, 2014 at 16:07 UTC
    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 may be slower, but detects ')(' as incorrect