in reply to IT's not counting...

  1. You are assigning an array to a scalar ($string = (@_)). Value of $string becomes a numeric representing the number of elements in @_
  2. $testString does not seem to be initialized
  3. You need not specify single quotes to enclose brackets. Escaping is enough.
  4. In your example only those brackets will be considered which have an digit following immediately.

Depending on how complex you want to be, the program may require many changes but taking the simplest approach, I think following will suit your requirements.

#!/usr/bin/perl use strict; sub parenth { my ($string) = (@_); my $l_count = () = ($string =~ /\(/g); my $r_count = () = ($string =~ /\)/g); if ($l_count != $r_count) { print "There is no balance on this line ($l_count vs $ +r_count)! Did you format it correctly???"; return 0; } else { print "There is balance in this universe"; return 1; } } my $test_string = 'x = (89 - 12)*( 1 + 2)'; parenth($test_string);

Replies are listed 'Best First'.
Re^2: IT's not counting...
by Dwood (Acolyte) on Nov 16, 2010 at 08:47 UTC
    @ point one: Oops, thanks for pointing that out! I was poring over perldoc trying to find stuff about subroutines and saw some things that mentioned exactly what you pointed out and didn't think anything of it...

    Lately my perl debug console has gone all wonky and completely refuses to give me the errors on a per-line basis so I have to hunt down the bugs for each time the errors occur...

    @ point two: Heh, yeah, I just noticed that testString wasn't initialized. Silly me, I was doing tests to see what would work and in my rush to post it, forgot to set it so that testString was $string.

    @ point three & four: Thanks, I'm new to regex and have been avoiding it because of the fairly famous quote that says something about using regex and the programmer now having 2 problems. (obfuscation not good for my diet of perl)

    What kind of changes do you mean?

    Also, thanks for helping me out here! Saved me some hours of searching around haha!
      What kind of changes do you mean?

      By "many changes" I mean that my approach is simply to match number of right brackets against number of left brackets which would return true even in following cases

      • $test_string = 'x = )(';
      • $test_string = 'x = 1*)))*2(((';
      etc.

      For additional constraints, you'll have to think about combination of possible correct/incorrect cases before you could claim that your script is working as expected.

        Oh Jeeze I didn't even think about those kinds of cases...

        For what I need I believe that as it checks each expression for validity (i'm interpreting lisp-like expressions) before it runs should rule that out. E.G. )+ <item1> <item2>)(( won't work because (in theory) )+ doesn't match up.

        Because you posted that, however I'm definitely posting up links to a repo/cpan module I make of this so those interested can stress-test what I make.