3.5. Ideographic Unary Operators
Most unary operators just have names (see Section 3.10, "Named Unary and File Test Operators" later in this chapter), but some operators are deemed important enough to merit their own special symbolic representation. All of these operators seem to have something to do with negation. Blame the mathematicians.
Unary ! performs logical negation, that is, "not". See not for a lower precedence version of logical negation. The value of a negated operand is true (1) if the operand is false (numeric 0, string "0", the null string, or undefined) and false ("") if the operand is true.
Unary - performs arithmetic negation if the operand is numeric. If the operand is an identifier, a string consisting of a minus sign concatenated with the identifier is returned. Otherwise, if the string starts with a plus or minus, a string starting with the opposite sign is returned. One effect of these rules is that -bareword is equivalent to "-bareword". This is most useful for Tk programmers.
Unary ~ performs bitwise negation, that is, 1's complement. By definition, this is somewhat nonportable when limited by the word size of your machine. For example, on a 32-bit machine, ~123 is 4294967172, while on a 64-bit machine, it's 18446744073709551492. But you knew that already.
What you perhaps didn't know is that if the argument to ~ happens to be a string instead of a number, a string of identical length is returned, but with all the bits of the string complemented. This is a fast way to flip a lot of bits all at once, and it's a way to flip those bits portably, since it doesn't depend on the word size of your computer. Later we'll also cover the bitwise logical operators, which have string-oriented variants as well.
Unary + has no semantic effect whatsoever, even on strings. It is syntactically useful for separating a function name from a parenthesized expression that would otherwise be interpreted as the complete list of function arguments. (See examples under the section Section 3.1, "Terms and List Operators (Leftward)".) If you think about it sideways, + negates the effect that parentheses have of turning prefix operators into functions.
Unary \ creates a reference to whatever follows it. Used on a list, it creates a list of references. See the section Section 3.2.1, "The Backslash Operator" in Chapter 8, "References" for details. Do not confuse this behavior with the behavior of backslash within a string, although both forms do convey the vaguely negational notion of protecting the next thing from interpretation. This resemblance is not entirely accidental.
Copyright © 2002 O'Reilly & Associates. All rights reserved.