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

typo @$; is not $@;

Replies are listed 'Best First'.
Re^3: Using qw to check for balanced parentheses
by jwkrahn (Abbot) on Feb 02, 2011 at 01:08 UTC

    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; }

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

        )( is balanced ))))(()((( is balanced
Re^3: Using qw to check for balanced parentheses
by unix_hacker_beard (Novice) on Feb 02, 2011 at 01:27 UTC
    D'oh! Thanks, I'm too used to dereferencing arrays.