in reply to How to insert || and && in an if loop

Using logical OR or AND works fine in if-conditions. but you most likely don't want to use the /g option in the regex match. Reason is this:

my $string = "foo:bar:baz:quux"; for (1..10) { print "$_\n"; if ($string=~m/:/g || length($string)!=16) { print "Either : already in string on the length is invalid\n"; } } __END__ 1 Either : already in string on the length is invalid 2 Either : already in string on the length is invalid 3 Either : already in string on the length is invalid 4 5 Either : already in string on the length is invalid 6 Either : already in string on the length is invalid 7 Either : already in string on the length is invalid 8 9 Either : already in string on the length is invalid 10 Either : already in string on the length is invalid

Note that it doesn't match on the 4th and 8th iteration. See the description of the match operator in perlop for why.

Replies are listed 'Best First'.
Re^2: How to insert || and && in an if loop
by AnomalousMonk (Archbishop) on Dec 17, 2011 at 22:33 UTC
    ... you most likely don't want to use the /g option ... [emphasis added]

    For advice to a monk inexperienced in both programming in general and Perl in perticular, I would promote "most likely don't" to "do not" (including the boldface) for the reason that your example demonstrates and perlop discusses: that it sets up a subtle (but still lethal!) pitfall that may ensnare even the most puissant monk. In fact, I would go farther and say that an inexperienced monk should never use the /g regex modifier unless he or she knows exactly why it is being used. (In fact, this would not be bad general advice for monks and programmers of every level of experience!)