4.5. OperatorsTable 4-3 lists all the Perl operators from highest to lowest precedence and indicates their associativity. Table 4-3. Perl associativity and operators, listed by precedence
You can clarify your expressions by using parentheses to group any part of an expression. Anything in parentheses will be evaluated as a single unit within a larger expression. With very few exceptions, Perl operators act upon scalar values only, not upon list values. Terms that take highest precedence in Perl include variables, quote and quotelike operators, any expression in parentheses, and any function with arguments in parentheses. A list operator is a function that can take a list of values as its argument. List operators take highest precedence when considering what's to the left of them. They have considerably lower precedence when looking to their right, which is the expected result. Also parsed as high-precedence terms are the do{} and eval{} constructs, as well as subroutine and method calls, the anonymous array and hash composers ([] and {}), and the anonymous subroutine composer sub{}. A unary operator is a function that takes a single scalar value as its argument. Unary operators have a lower precedence than list operators because they expect and take only one value. 4.5.1. The Arrow OperatorThe arrow operator is a dereference operator. It can be used for references to arrays, hashes, code references, or for calling methods on objects. See the discussion of references in Chapter 7, "Packages, Modules, and Objects". 4.5.2. Unary OperatorsUnary ! performs logical negation, that is, "not." The not operator is a lower-precedence version of !. Unary - performs arithmetic negation if the operand is numeric. If the operand is an identifier, then 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. Unary ~ performs bitwise negation, that is, one's complement. For example, on a 32-bit machine, ~0xFF is 0xFFFFFF00. If the argument to ~ is a string instead of a number, a string of identical length is returned, but with all the bits of the string complemented. 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. Unary \ creates a reference to whatever follows it (see Section 4.8, "References and Complex Data Structures" later in this chapter). Do not confuse this behavior with the behavior of the backslash within a string. The \ operator may also be used on a parenthesized list value in a list context, in which case it returns references to each element of the list. 4.5.3. Arithmetic OperatorsBinary ** is the exponentiation operator. Note that it binds even more tightly than unary minus, so -2**4 is -(2**4), not (-2)**4. Also note that ** has right associativity, so: $e = 2 ** 3 ** 4; evaluates to 2 to the 81st power, not 8 to the 4th power. The * (multiply) and / (divide) operators work exactly as you might expect, multiplying or dividing their two operands. Division is done in floating-point mode, unless integer mode in enabled (via use integer). The % (modulus) operator converts its operands to integers before finding the remainder according to integer division. For the same operation in floating-point mode, you may prefer to use the fmod( ) function from the POSIX module (see Chapter 8, "Standard Modules"). 4.5.4. Comparison OperatorsComparison operators can be categorized into relational and equality operators. 4.5.4.1. Relational operatorsPerl has two classes of relational operators. One class operates on numeric values, and the other operates on string values. String comparisons are based on the ASCII collating sequence. Relational operators are nonassociative, so $a < $b < $c is a syntax error.
4.5.4.2. Equality operatorsThe equal and not-equal operators return 1 for true and "" for false (just as the relational operators do). The <=> and cmp operators return -1 if the left operand is less than the right operand, 0 if they are equal, and +1 if the left operand is greater than the right.
4.5.5. Autoincrement and AutodecrementIf placed before a variable, the ++ and -- operators increment or decrement the variable before returning the value. If placed after, they increment or decrement the variable after returning the value. 4.5.6. Assignment OperatorsPerl recognizes the following operators for assigning a value to a variable: = **= += *= &= <<= &&= -= /= |= >>= ||= .= %= ^= x= Each operator requires a variable on the left side and an expression on the right side. For the simple assignment operator, =, the value of the expression is stored in the designated variable. For the other operators, Perl evaluates the expression: $var OP= $value as if it was written: $var = $var OP $value except that $var is evaluated only once. For example: $a += 2; # Same as $a = $a + 2 4.5.7. Pattern Match OperatorsBinary =~ binds a scalar expression to a pattern match, substitution, or translation. These operations search or modify the string $_ by default. Binary !~ is just like =~ except the return value is negated in the logical sense. The following expressions are functionally equivalent: $string !~ /pattern/ not $string =~ /pattern/ see Section 4.6, "Regular Expressions" later in this chapter. 4.5.8. File Test OperatorsA file test operator is a unary operator that tests a filename or a filehandle.
4.5.9. Logical OperatorsPerl provides the && (logical AND) and || (logical OR) operators. They evaluate from left to right testing the truth of the statement.
For example, an oft-appearing idiom in Perl programs is: open(FILE, "somefile") || die "Cannot open somefile: $!\n"; In this case, Perl first evaluates the open function. If the value is true (because somefile was successfully opened), the execution of the die function is unnecessary and is skipped. Perl also provides lower-precedence and and or operators that are more readable. 4.5.10. Bitwise OperatorsPerl has bitwise AND, OR, and XOR (exclusive OR) operators: &, |, and ^. These operators work differently on numeric values than they do on strings. If either operand is a number, then both operands are converted to integers, and the bitwise operation is performed between the two integers. If both operands are strings, these operators do bitwise operations between corresponding bits from the two strings. 4.5.11. Miscellaneous OperatorsThe following operators don't fit into any of the previous categories. 4.5.11.1. Range operatorThe .. range operator is really two different operators depending on the context. In a list context, it returns a list of values counting (by ones) from the left value to the right value. In a scalar context, .. returns a Boolean value. It is false as long as its left operand is false. Once the left operand is true, the range operator stays true until the right operand is true, after which the range operator becomes false again. The right operand is not evaluated while the operator is in the false state, and the left operand is not evaluated while the operator is in the true state. The alternate version of this operator, ..., does not test the right operand immediately when the operator becomes true; it waits until the next evaluation. 4.5.11.2. Conditional operatorTernary ?: is the conditional operator. It works like an if-then-else statement but can safely be embedded within other operations and functions: test_expr ? if_true_expr : if_false_expr If the test_expr is true, only the if_true_expr is evaluated. Otherwise, only the if_false_expr is evaluated. Either way, the value of the evaluated expression becomes the value of the entire expression. 4.5.11.3. Comma operatorIn a list context, , is the list argument separator and inserts both its arguments into the list. In scalar context, , evaluates its left argument, throws that value away, then evaluates its right argument and returns that value. The => operator is mostly just a synonym for the comma operator. It's useful for documenting arguments that come in pairs. It also forces any identifier to the left of it to be interpreted as a string. 4.5.11.4. String operatorThe concatenation operator . is used to add strings together: print 'abc' . 'def'; # Prints abcdef print $a . $b; # Concatenates the string values of $a and $b Binary x is the string repetition operator. In scalar context, it returns a concatenated string consisting of the left operand repeated the number of times specified by the right operand: print '-' x 80; # Prints row of dashes print "\t" x ($tab/8), ' ' x ($tab%8); # Tabs over In list context, if the left operand is a list in parentheses, the x works as a list replicator rather than a string replicator. This is useful for initializing all the elements of an array of indeterminate length to the same value: @ones = (1) x 80; # A list of 80 1s @ones = (5) x @ones; # Set all elements to 5 Copyright © 2002 O'Reilly & Associates. All rights reserved. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|