in reply to Using qw to check for balanced parentheses

It took a long time and didn't give me the right answer for some reason:

Is );system('rm -rf /');# balanced? ~$#& NO CARRIER

Update: While I was trying to get back into that server I whipped up how I'd do this:

sub balanced { my( $str )= @_; my $d= 0; while( $str =~ m(([(])|([)]))g ) { if( $1 ) { $d++; } elsif( --$d < 0 ) { return 0; } } return 0 == $d; }

- tye        

Replies are listed 'Best First'.
Re^2: Using qw to check for balanced parentheses (oops)
by jdporter (Paladin) on Sep 16, 2011 at 19:06 UTC
    sub balanced { local $_ = shift; s/[^()]//g; eval "qw($_)"; ! $@ }

      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

      Very nice!

      - tye