Remix.run Logo
lkbm 4 hours ago

> !! Bang bang boolean conversion

This isn't a special operator. This is just how "not" (!) works. In basically every language: C, C++, Javascript, Perl, etc., ! is the "not" operator so !12 gives you false (12 is truthy), and !!12 (not false) gives you true.

It's the same in languages that use different operators for "not". In python, the "not" operator is just the word not, and can write "not not 12" to get True. They didn't implement a special "not not" operator, anymore than Perl implemented a "!!" operator. They just implemented the basic ! / "not" operator.

stearns 4 hours ago | parent | next [-]

Right, that's the point of TFA. It doesn't list "special" operators, it lists "secret" operators -- that is, operators combined from existing sigils that do clever things.

The "Venus" operator is a good example: it's the '+' addition operator! You just add zero to a value that's coercible into a number.

The Eskimo operators are also interesting: similar to a SQL injection attack, you use a close brace and an open brace to stop and start a new code block from within a string that's sent to the interpreter. Perl didn't invent open and close braces: hence the verb "discover" rather than "implement".

The whole page is a bit of a lark, and a good example of why some of us don't enjoy Perl!

lkbm 4 hours ago | parent [-]

Fair point. I should've read more before jumping in here with my first reaction.

johnisgood 4 hours ago | parent | prev [-]

Keep in mind that applying the logical NOT operator twice (using `!!`) converts any integer expression into a strict boolean.

Any non-zero value becomes `1`, and zero remains `0`. This is commonly used for boolean normalization when the original expression yields a bitmask or arbitrary integer.

While the same result can be written as `(x != 0)`, the `!!x` idiom is concise, widely used in low-level C code, guarantees a result of exactly `0` or `1`, and works well in macros and constant expressions.

lkbm 3 hours ago | parent [-]

Fair, I forgot that C bools are just 0 and 1. That's where I first learned the !! trick, but it's been many a year.

defrost 3 hours ago | parent [-]

Err, C bools have two interpreted values, TRUE, and FALSE.

Confusingly (to some) they are integers and while 0 represents FALSE, any non 0 value represents TRUE.

It's pedantic, apologies, but that is why the GP refers to "convert to strict boolean"