in reply to Re^2: Using qw to check for balanced parentheses
in thread Using qw to check for balanced parentheses

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

Replies are listed 'Best First'.
Re^4: Using qw to check for balanced parentheses
by ikegami (Patriarch) on Feb 02, 2011 at 02:00 UTC
    That won't handle "" hand "0", but that's easy to fix:
    sub is_balanced { eval "qw($_[0]); 1" }
Re^4: Using qw to check for balanced parentheses
by Anonymous Monk on Feb 02, 2011 at 01:13 UTC
    sub is_balanced2 { not    $_[0] =~ tr/)(//    % 2; }

      Update: nothing but down votes for this...? This is output from using the above snippet, not suggested results.

      )( is balanced ))))(()((( is balanced
        balance is in the eye of the beholder