Main Content

Saying NOT in Perl, PHP, Python, Lua ...

Archive - Originally posted on "The Horse's Mouth" - 2008-07-04 21:04:03 - Graham Ellis

"Isn't there one standard way to say NOT?" asked one of my delegates on today's course - and it's an excellent question. But the answer to a question about a negative subject is itself in the negative - no, there isn't just a single way!

In fact .. I can think of no fewer that 12 ways!

• 1. ! The ! is the unary not operator in a wide range of languages.

• 2. != Using != means "does not equal". In languages such as C and PHP, it checks the contents of the variables, and in Perl it checks whether two values are numerically the same. In many OO languages, the operator is (or can be) overridden to mean something of your own choice.

• 3. <> This operator in some languages Perl is an alternative to the the != operator.

• 4. ~= In Lua, instead of using != to mean not equals, you used ~=.

• 5. ^ The caret character is used to indicate NOT on of in a regular expression group, and it has the same meaning in Lua's pattern matching too. For example ... [^aeiou] means match any one character which is not a lower case vowel.

• 6. not The word not operates in the same way as the ! operator in many languages. However - it has a different place in the operator precedence tree which means that you'll sometimes need to use round brackets in different places with not and with !.

• 7. capitalisation In a regular expression in Perl, and in Perl-like regular expression such as PHP's preg functions and Python, you can invert a charactered group b y capitalising the letter. So \s means a space character, but \S means a none-space. Capitalisation also applies in this way in Lua's pattern matching - so for example %a matches an alphabetic character, but %A matches a none-alpha.

• 8. unless In Perl, an unless statement may be used to cause a block of code to be performed only if a condition is NOT true.

• 9. until You'll find until loops in Perl and Lua - a block of code is repeated while a condition is NOT true (i.e. until it is true).

• 10. ne Perl's ne operator checks whether strings are equal. And the -ne operator in shell programming checks whether numbers are equal, using the == operator that Perl uses for numbers for strings instead. (This sort of difference really helps to keep me on my toes when I'm training!)

• 11. !~ "Does not match ..." a regular expression. Perl.

• 12. !== "Is not identical to" in PHP. The difference between !== and != is that the latter operator will return false (indicating two values are equal) if you compare the number zero to either the string 0, or an empty string, or a variable that does not exist. The former will ONLY return false if you compare two values of the same type that have the same value.