home *** CD-ROM | disk | FTP | other *** search
- <!-- $RCSfile$$Revision$$Date$ -->
- <!-- $Log$ -->
- <HTML>
- <TITLE> PERLOP </TITLE>
- <h2>NAME</h2>
- perlop - Perl operators and precedence
- <p><h2>SYNOPSIS</h2>
- Perl operators have the following associativity and precedence,
- listed from highest precedence to lowest. Note that all operators
- borrowed from C keep the same precedence relationship with each other,
- even where C's precedence is slightly screwy. (This makes learning
- Perl easier for C folks.)
- <p>
- <listing>
- left terms and list operators (leftward)
- left ->
- nonassoc ++ --
- right **
- right ! ~ \ and unary + and -
- left =~ !~
- left * / % x
- left + - .
- left <<>>
- nonassoc named unary operators
- nonassoc < > <= >= lt gt le ge
- nonassoc == != <=> eq ne cmp
- left &
- left | ^
- left &&
- left ||
- nonassoc ..
- right ?:
- right = += -= *= etc.
- left , =>
- nonassoc list operators (rightward)
- left not
- left and
- left or xor
- </listing>
- In the following sections, these operators are covered in precedence order.
- <p><h2>DESCRIPTIONS</h2>
- <h3>Terms and List Operators (Leftward)</h3>
- Any TERM is of highest precedence of Perl. These includes variables,
- quote and quotelike operators, any expression in parentheses,
- and any function whose arguments are parenthesized. Actually, there
- aren't really functions in this sense, just list operators and unary
- operators behaving as functions because you put parentheses around
- the arguments. These are all documented in
- <A HREF="perlfunc.html">
- the perlfunc manpage</A>
- .
- <p>If any list operator (print(), etc.) or any unary operator (chdir(), etc.)
- is followed by a left parenthesis as the next token, the operator and
- arguments within parentheses are taken to be of highest precedence,
- just like a normal function call.
- <p>In the absence of parentheses, the precedence of list operators such as
-
- <A HREF="perlfunc.html#perlfunc_189">print</A>
- ,
- <A HREF="perlfunc.html#perlfunc_234">sort</A>
- , or
- <A HREF="perlfunc.html#perlfunc_81">chmod</A>
- is either very high or very low depending on
- whether you look at the left side of operator or the right side of it.
- For example, in
- <p><pre>
- @ary = (1, 3, sort 4, 2);
- print @ary; # prints 1324
- </pre>
- the commas on the right of the sort are evaluated before the sort, but
- the commas on the left are evaluated after. In other words, list
- operators tend to gobble up all the arguments that follow them, and
- then act like a simple TERM with regard to the preceding expression.
- Note that you have to be careful with parens:
- <p><pre>
- # These evaluate exit before doing the print:
- print($foo, exit); # Obviously not what you want.
- print $foo, exit; # Nor is this.
- </pre>
- <pre>
- # These do the print before evaluating exit:
- (print $foo), exit; # This is what you want.
- print($foo), exit; # Or this.
- print ($foo), exit; # Or even this.
- </pre>
- Also note that
- <p><pre>
- print ($foo & 255) + 1, "\n";
- </pre>
- probably doesn't do what you expect at first glance. See
-
- <A HREF="perlop.html#perlop_301">Named Unary Operators</A>
- for more discussion of this.
- <p>Also parsed as terms are the <B>do {}</B> and <B>eval {}</B> constructs, as
- well as subroutine and method calls, and the anonymous
- constructors <B>[]</B> and <B>{}</B>.
- <p>See also
- <A HREF="perlop.html#perlop_319">Quote and Quotelike Operators</A>
- toward the end of this section,
- as well as
- <A HREF="perlop.html#perlop_329">I/O Operators</A>
- .
- <p><h3>The Arrow Operator</h3>
- Just as in C and C++, "<B>-></B>" is an infix dereference operator. If the
- right side is either a <B>[...]</B> or <B>{...}</B> subscript, then the left side
- must be either a hard or symbolic reference to an array or hash (or
- a location capable of holding a hard reference, if it's an lvalue (assignable)).
- See
- <A HREF="perlref.html">
- the perlref manpage</A>
- .
- <p>Otherwise, the right side is a method name or a simple scalar variable
- containing the method name, and the left side must either be an object
- (a blessed reference) or a class name (that is, a package name).
- See
- <A HREF="perlobj.html">
- the perlobj manpage</A>
- .
- <p><h3>Autoincrement and Autodecrement</h3>
- "++" and "--" work as in C. That is, if placed before a variable, they
- increment or decrement the variable before returning the value, and if
- placed after, increment or decrement the variable after returning the value.
- <p>The autoincrement operator has a little extra built-in magic to it. If
- you increment a variable that is numeric, or that has ever been used in
- a numeric context, you get a normal increment. If, however, the
- variable has only been used in string contexts since it was set, and
- has a value that is not null and matches the pattern
- <B>/^[a-zA-Z]*[0-9]*$/</B>, the increment is done as a string, preserving each
- character within its range, with carry:
- <p><pre>
- print ++($foo = '99'); # prints '100'
- print ++($foo = 'a0'); # prints 'a1'
- print ++($foo = 'Az'); # prints 'Ba'
- print ++($foo = 'zz'); # prints 'aaa'
- </pre>
- The autodecrement operator is not magical.
- <p><h3>Exponentiation</h3>
- Binary "**" is the exponentiation operator. Note that it binds even more
- tightly than unary minus, so -2**4 is -(2**4), not (-2)**4.
- <p><h3>Symbolic Unary Operators</h3>
- Unary "!" performs logical negation, i.e. "not". See also <B>not</B> for a lower
- precedence version of this.
- <p>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 <B>-bareword</B> is equivalent
- to <B>"-bareword"</B>.
- <p>Unary "~" performs bitwise negation, i.e. 1's complement.
- <p>Unary "+" has no effect whatsoever, even on strings. It is useful
- syntactically for separating a function name from a parenthesized expression
- that would otherwise be interpreted as the complete list of function
- arguments. (See examples above under List Operators.)
- <p>Unary "\" creates a reference to whatever follows it. See
- <A HREF="perlref.html">
- the perlref manpage</A>
- .
- Do not confuse this behavior with the behavior of backslash within a
- string, although both forms do convey the notion of protecting the next
- thing from interpretation.
- <p><h3>Binding Operators</h3>
- Binary "=~" binds an expression to a pattern match.
- Certain operations search or modify the string $_ by default. This
- operator makes that kind of operation work on some other string. The
- right argument is a search pattern, substitution, or translation. The
- left argument is what is supposed to be searched, substituted, or
- translated instead of the default $_. The return value indicates the
- success of the operation. (If the right argument is an expression
- rather than a search pattern, substitution, or translation, it is
- interpreted as a search pattern at run time. This is less efficient
- than an explicit search, since the pattern must be compiled every time
- the expression is evaluated--unless you've used <B>/o</B>.)
- <p>Binary "!~" is just like "=~" except the return value is negated in
- the logical sense.
- <p><h3>Multiplicative Operators</h3>
- Binary "*" multiplies two numbers.
- <p>Binary "/" divides two numbers.
- <p>Binary "%" computes the modulus of the two numbers.
- <p>Binary "x" is the repetition operator. In a scalar context, it
- returns a string consisting of the left operand repeated the number of
- times specified by the right operand. In a list context, if the left
- operand is a list in parens, it repeats the list.
- <p><pre>
- print '-' x 80; # print row of dashes
- </pre>
- <pre>
- print "\t" x ($tab/8), ' ' x ($tab%8); # tab over
- </pre>
- <pre>
- @ones = (1) x 80; # a list of 80 1's
- @ones = (5) x @ones; # set all elements to 5
- </pre>
- <h3>Additive Operators</h3>
- Binary "+" returns the sum of two numbers.
- <p>Binary "-" returns the difference of two numbers.
- <p>Binary "." concatenates two strings.
- <p><h3>Shift Operators</h3>
- Binary "<<" returns the value of its left argument shifted left by the
- number of bits specified by the right argument. Arguments should be
- integers.
- <p>Binary >>" returns the value of its left argument shifted right by the
- number of bits specified by the right argument. Arguments should be
- integers.
- <p><h3>Named Unary Operators</h3>
- The various named unary operators are treated as functions with one
- argument, with optional parentheses. These include the filetest
- operators, like <B>-f</B>, <B>-M</B>, etc. See
- <A HREF="perlfunc.html">
- the perlfunc manpage</A>
- .
- <p>If any list operator (print(), etc.) or any unary operator (chdir(), etc.)
- is followed by a left parenthesis as the next token, the operator and
- arguments within parentheses are taken to be of highest precedence,
- just like a normal function call. Examples:
- <p><pre>
- chdir $foo || die; # (chdir $foo) || die
- chdir($foo) || die; # (chdir $foo) || die
- chdir ($foo) || die; # (chdir $foo) || die
- chdir +($foo) || die; # (chdir $foo) || die
- </pre>
- but, because * is higher precedence than ||:
- <p><pre>
- chdir $foo * 20; # chdir ($foo * 20)
- chdir($foo) * 20; # (chdir $foo) * 20
- chdir ($foo) * 20; # (chdir $foo) * 20
- chdir +($foo) * 20; # chdir ($foo * 20)
- </pre>
- <pre>
- rand 10 * 20; # rand (10 * 20)
- rand(10) * 20; # (rand 10) * 20
- rand (10) * 20; # (rand 10) * 20
- rand +(10) * 20; # rand (10 * 20)
- </pre>
- See also "List Operators".
- <p><h3>Relational Operators</h3>
- Binary "<" returns true if the left argument is numerically less than
- the right argument.
- <p>Binary ">" returns true if the left argument is numerically greater
- than the right argument.
- <p>Binary "<=" returns true if the left argument is numerically less than
- or equal to the right argument.
- <p>Binary ">=" returns true if the left argument is numerically greater
- than or equal to the right argument.
- <p>Binary "lt" returns true if the left argument is stringwise less than
- the right argument.
- <p>Binary "gt" returns true if the left argument is stringwise greater
- than the right argument.
- <p>Binary "le" returns true if the left argument is stringwise less than
- or equal to the right argument.
- <p>Binary "ge" returns true if the left argument is stringwise greater
- than or equal to the right argument.
- <p><h3>Equality Operators</h3>
- Binary "==" returns true if the left argument is numerically equal to
- the right argument.
- <p>Binary "!=" returns true if the left argument is numerically not equal
- to the right argument.
- <p>Binary "<=>" returns -1, 0, or 1 depending on whether the left argument is numerically
- less than, equal to, or greater than the right argument.
- <p>Binary "eq" returns true if the left argument is stringwise equal to
- the right argument.
- <p>Binary "ne" returns true if the left argument is stringwise not equal
- to the right argument.
- <p>Binary "cmp" returns -1, 0, or 1 depending on whether the left argument is stringwise
- less than, equal to, or greater than the right argument.
- <p><h3>Bitwise And</h3>
- Binary "&" returns its operators ANDed together bit by bit.
- <p><h3>Bitwise Or and Exclusive Or</h3>
- Binary "|" returns its operators ORed together bit by bit.
- <p>Binary "^" returns its operators XORed together bit by bit.
- <p><h3>C-style Logical And</h3>
- Binary "&&" performs a short-circuit logical AND operation. That is,
- if the left operand is false, the right operand is not even evaluated.
- Scalar or list context propagates down to the right operand if it
- is evaluated.
- <p><h3>C-style Logical Or</h3>
- Binary "||" performs a short-circuit logical OR operation. That is,
- if the left operand is true, the right operand is not even evaluated.
- Scalar or list context propagates down to the right operand if it
- is evaluated.
- <p>The <B>||</B> and <B>&&</B> operators differ from C's in that, rather than returning
- 0 or 1, they return the last value evaluated. Thus, a reasonably portable
- way to find out the home directory (assuming it's not "0") might be:
- <p><pre>
- $home = $ENV{'HOME'} || $ENV{'LOGDIR'} ||
- (getpwuid($<))[7] || die "You're homeless!\n";
- </pre>
- As more readable alternatives to <B>&&</B> and <B>||</B>, Perl provides "and" and
- "or" operators (see below). The short-circuit behavior is identical. The
- precedence of "and" and "or" is much lower, however, so that you can
- safely use them after a list operator without the need for
- parentheses:
- <p><pre>
- unlink "alpha", "beta", "gamma"
- or gripe(), next LINE;
- </pre>
- With the C-style operators that would have been written like this:
- <p><pre>
- unlink("alpha", "beta", "gamma")
- || (gripe(), next LINE);
- </pre>
- <h3>Range Operator</h3>
- Binary ".." is the range operator, which is really two different
- operators depending on the context. In a list context, it returns an
- array of values counting (by ones) from the left value to the right
- value. This is useful for writing <B>for (1..10)</B> loops and for doing
- slice operations on arrays. Be aware that under the current implementation,
- a temporary array is created, so you'll burn a lot of memory if you
- write something like this:
- <p><pre>
- for (1 .. 1_000_000) {
- # code
- }
- </pre>
- In a scalar context, ".." returns a boolean value. The operator is
- bistable, like a flip-flop, and emulates the line-range (comma) operator
- of <B>sed</B>, <B>awk</B>, and various editors. Each ".." operator maintains its
- own boolean state. 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, <I>AFTER</I> which the range operator becomes false
- again. (It doesn't become false till the next time the range operator is
- evaluated. It can test the right operand and become false on the same
- evaluation it became true (as in <B>awk</B>), but it still returns true once.
- If you don't want it to test the right operand till the next evaluation
- (as in <B>sed</B>), use three dots ("...") instead of two.) 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 precedence is a little lower than || and &&. The value
- returned is either the null string for false, or a sequence number
- (beginning with 1) for true. The sequence number is reset for each range
- encountered. The final sequence number in a range has the string "E0"
- appended to it, which doesn't affect its numeric value, but gives you
- something to search for if you want to exclude the endpoint. You can
- exclude the beginning point by waiting for the sequence number to be
- greater than 1. If either operand of scalar ".." is a numeric literal,
- that operand is implicitly compared to the
- <A HREF="perlvar.html#perlvar_386">$.</A>
- variable, the current
- line number. Examples:
- <p>As a scalar operator:
- <p><pre>
- if (101 .. 200) { print; } # print 2nd hundred lines
- next line if (1 .. /^$/); # skip header lines
- s/^/> / if (/^$/ .. eof()); # quote body
- </pre>
- As a list operator:
- <p><pre>
- for (101 .. 200) { print; } # print $_ 100 times
- @foo = @foo[$[ .. $#foo]; # an expensive no-op
- @foo = @foo[$#foo-4 .. $#foo]; # slice last 5 items
- </pre>
- The range operator (in a list context) makes use of the magical
- autoincrement algorithm if the operaands are strings. You
- can say
- <p><pre>
- @alphabet = ('A' .. 'Z');
- </pre>
- to get all the letters of the alphabet, or
- <p><pre>
- $hexdigit = (0 .. 9, 'a' .. 'f')[$num & 15];
- </pre>
- to get a hexadecimal digit, or
- <p><pre>
- @z2 = ('01' .. '31'); print $z2[$mday];
- </pre>
- to get dates with leading zeros. If the final value specified is not
- in the sequence that the magical increment would produce, the sequence
- goes until the next value would be longer than the final value
- specified.
- <p><h3>Conditional Operator</h3>
- Ternary "?:" is the conditional operator, just as in C. It works much
- like an if-then-else. If the argument before the ? is true, the
- argument before the : is returned, otherwise the argument after the :
- is returned. Scalar or list context propagates downward into the 2nd
- or 3rd argument, whichever is selected. The operator may be assigned
- to if both the 2nd and 3rd arguments are legal lvalues (meaning that you
- can assign to them):
- <p><pre>
- ($a_or_b ? $a : $b) = $c;
- </pre>
- Note that this is not guaranteed to contribute to the readability of
- your program.
- <p><h3>Assigment Operators</h3>
- "=" is the ordinary assignment operator.
- <p>Assignment operators work as in C. That is,
- <p><pre>
- $a += 2;
- </pre>
- is equivalent to
- <p><pre>
- $a = $a + 2;
- </pre>
- although without duplicating any side effects that dereferencing the lvalue
- might trigger, such as from tie(). Other assignment operators work similarly.
- The following are recognized:
- <p><pre>
- **= += *= &= <<= &&=
- -= /= |= >>= ||=
- .= %= ^=
- x=
- </pre>
- Note that while these are grouped by family, they all have the precedence
- of assignment.
- <p>Unlike in C, the assignment operator produces a valid lvalue. Modifying
- an assignment is equivalent to doing the assignment and then modifying
- the variable that was assigned to. This is useful for modifying
- a copy of something, like this:
- <p><pre>
- ($tmp = $global) =~ tr [A-Z] [a-z];
- </pre>
- Likewise,
- <p><pre>
- ($a += 2) *= 3;
- </pre>
- is equivalent to
- <p><pre>
- $a += 2;
- $a *= 3;
- </pre>
- <h3></h3>
- Binary "," is the comma operator. In a scalar context it evaluates
- its left argument, throws that value away, then evaluates its right
- argument and returns that value. This is just like C's comma operator.
- <p>In a list context, it's just the list argument separator, and inserts
- both its arguments into the list.
- <p><h3>List Operators (Rightward)</h3>
- On the right side of a list operator, it has very low precedence,
- such that it controls all comma-separated expressions found there.
- The only operators with lower precedence are the logical operators
- "and", "or", and "not", which may be used to evaluate calls to list
- operators without the need for extra parentheses:
- <p><pre>
- open HANDLE, "filename"
- or die "Can't open: $!\n";
- </pre>
- See also discussion of list operators in List Operators (Leftward).
- <p><h3>Logical Not</h3>
- Unary "not" returns the logical negation of the expression to its right.
- It's the equivalent of "!" except for the very low precedence.
- <p><h3>Logical And</h3>
- Binary "and" returns the logical conjunction of the two surrounding
- expressions. It's equivalent to && except for the very low
- precedence. This means that it short-circuits: i.e. the right
- expression is evaluated only if the left expression is true.
- <p><h3>Logical or and Exclusive Or</h3>
- Binary "or" returns the logical disjunction of the two surrounding
- expressions. It's equivalent to || except for the very low
- precedence. This means that it short-circuits: i.e. the right
- expression is evaluated only if the left expression is false.
- <p>Binary "xor" returns the exclusive-OR of the two surrounding expressions.
- It cannot short circuit, of course.
- <p><h3>C Operators Missing From Perl</h3>
- Here is what C has that Perl doesn't:
- <p>
- <dl>
-
- <dt><b><A NAME="perlop_317">unary &</A></b>
- <dd>
- Address-of operator. (But see the "\" operator for taking a reference.)
- <p></dd>
- <dt><B>unary *</B>
- <dd>
- Dereference-address operator. (Perl's prefix dereferencing
- operators are typed: $, @, %, and &.)
- <p></dd>
-
- <dt><b><A NAME="perlop_318">(TYPE)</A></b>
- <dd>
- Type casting operator.
- <p></dd>
-
- </dl>
-
- <h3>Quote and Quotelike Operators</h3>
- While we usually think of quotes as literal values, in Perl they
- function as operators, providing various kinds of interpolating and
- pattern matching capabilities. Perl provides customary quote characters
- for these behaviors, but also provides a way for you to choose your
- quote character for any of them. In the followi<h1>Error</h1>
- Unable to load requested item for reason: -201
-