in reply to if var isnt used

Two things:

  1. The construct (.+|) will match one or more of any character (".+")or nothing ("|)"). So if no value is given there, the regex will match on nothing and return that into $a. Nothing in this case is the empty string, which is not equivalent to undef. To test for this you could test for truth instead of definedness (if($a)), but it'd be much better to specify the fact that $a is optional with the explicit "?", i.e. (.+)? instead of (.+|). The same goes for the other places where you use "|)".
  2. Don't use the variables $a and $b like this, they are special variables (see perldoc perlvar) and you can run into strange errors when using them (or at least make your code hard to understand and maintain).
  3. Update: Check out bobfs excellent node True or False? A quick Reference Guide for more on this.


Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -- Brian W. Kernighan

Replies are listed 'Best First'.
Re^2: if var isnt used
by metalfan (Novice) on Dec 24, 2005 at 14:26 UTC
    my ($vorzeichen_a_form,$a_form,$vorzeichen_b_seit,$b_seit,$vorzeichen_c_yab, $c_yab) = ($formel =~ m/y=

    (+\-)? #$vorzeichen_a_form
    (.+)? #$a_form
    x\^2 #x^2
    (+\-.+)? #$vorzeichen_b_seit, $b_seit
    (+\-.+)? #$vorzeichen_c_yab, $c_yab
    $/x);

    it should work on these combinations:
    y=x^2 #no a, b,c
    y=-x^2

    y=1x^2 #no b,c
    y=-1x^2

    y=x^2-2 #no b
    y=-1x^2-2
    y=1x^2-2

    y=x^2-2x #no c
    y=-1x^2-2x
    y=1x^2-2x

    y=x^2-2x-2 #a,b, and c are present
    y=-1x^2-2x-2
    y=1x^2-2x-2

    ofcourse, positive values are possible
    and ofcourse my idea doesnt work :(

      I second hollis suggestion, but here's a regex that does this anyway:

      while($formel=<DATA>) { my ($vorzeichen_a_form, $a_form, $vorzeichen_b_seit, $b_seit, $vorzeichen_c_yab, $c_yab) = $formel =~ m/y\s*=\s* ([-+])? #$vorzeichen_a_form (\d+)? #$a_form x\^2\s* (?: # non-capturing parentheses ([-+])? #$vorzeichen_b_seit (\d+)? #$b_seit x\s* )? # make this part optional (?: ([-+])? #$vorzeichen_c_yab (\d+)? #$c_yab )? /x; print join(":",($vorzeichen_a_form, $a_form, $vorzeichen_b_seit, $b_seit, $vorzeichen_c_yab, $c_yab))."\n"; } __DATA__ y=x^2 #no a, b,c y=-x^2 y=1x^2 #no b,c y=-1x^2 y=x^2-2 #no b y=-1x^2-2 y=1x^2-2 y=x^2-2x #no c y=-1x^2-2x y=1x^2-2x y=x^2-2x-2 #a,b, and c are present y=-1x^2-2x-2 y=1x^2-2x-2

      A computer is a state machine. Threads are for people who can't program state machines. -- Alan Cox