in reply to if multiple conditions & Warinings....

Below the text area when posting you could have seen some tips on how to write a post. <code> tags would have been useful there. UPG: Or Markup in the Monastery could be a useful read.

For you problem ne compares two strings, which /^[+-]\d+$/ is not. It's a matching operation (it's actually m/EXPR/ but with / delimiters around the expression the m can be omitted), which you can use on a string with the binding operator =~ see Binding Operators. And you want to check that $VAR1 is a number before making a number comparison with it. So that's if ($VAR1 !~ /^[\-+]?\d+$/ || $VAR1 != 2).

The next problem: - has a special meaning in a character range, so you have to escape it with \. Putting it in the first place is actually an exception to that, because it isn't ambiguous, but you can escape your - nonetheless, better safe than sorry.

At last, since you seem to be discovering Perl, do turn on warnings and strict, don't wait until you find a bug.

UPG: and maybe unless could make your code easier to read. And I don't see why you would include negative numbers if you're only looking for values different than 2. So you could actually write unless ($VAR1 =~ /^\+?2$/) { do some stuff }

Replies are listed 'Best First'.
Re^2: if multiple conditions & Warinings....
by AnomalousMonk (Archbishop) on Aug 22, 2013 at 01:50 UTC
    For you problem  ne compares two strings, which  /^[+-]\d+$/ is not.

    Actually, the problem with the  $VAR1 ne /^[+-]?\d+$/ expression in the OPed code is much more pernicious. In the absence of a  =~ binding operator,  // matches against the  $_ default scalar. If this scalar has a defined value, there will be no warning even if warnings are enabled. The  // match occurs in scalar context imposed by the  ne comparison operator. In scalar context,  // returns 1 (true) if there is a match and '' (empty string: false) if not. The  ne operator will stringize a 1 returned from a successful match. The  ne operator will stringize  $VAR1 and compare that against whatever resulted from the  // match. If  $VAR1 is defined, there will be no warning if warnings are enabled. Most of the values one can imagine  $VAR1 to contain will not (stringwise) equal either '1' or the empty string, thus setting the stage for very puzzling behavior.

    So even with strictures and warnings enabled, you might have been left with a devilish bug. Well, Perl is neither magical nor telepathic. There has to be some reason for the existence of the programmer, and that's why we earn the Big Buck$.