home *** CD-ROM | disk | FTP | other *** search
/ RISC DISC 2 / RISC_DISC_2.iso / pd_share / utilities / cli / perl / !Perl / Manual / perlop < prev    next >
Encoding:
Text File  |  1995-04-18  |  20.5 KB  |  480 lines

  1. <!-- $RCSfile$$Revision$$Date$ -->
  2. <!-- $Log$ -->
  3. <HTML>
  4. <TITLE> PERLOP </TITLE>
  5. <h2>NAME</h2>
  6. perlop - Perl operators and precedence
  7. <p><h2>SYNOPSIS</h2>
  8. Perl operators have the following associativity and precedence,
  9. listed from highest precedence to lowest.  Note that all operators
  10. borrowed from C keep the same precedence relationship with each other,
  11. even where C's precedence is slightly screwy.  (This makes learning
  12. Perl easier for C folks.)
  13. <p>
  14. <listing>
  15.     left    terms and list operators (leftward) 
  16.     left    -> 
  17.     nonassoc    ++ -- 
  18.     right    ** 
  19.     right    ! ~ \ and unary + and - 
  20.     left    =~ !~  
  21.     left    * / % x 
  22.     left    + - . 
  23.     left    <<>> 
  24.     nonassoc    named unary operators 
  25.     nonassoc    < > <= >= lt gt le ge 
  26.     nonassoc    == != <=> eq ne cmp 
  27.     left    & 
  28.     left    | ^ 
  29.     left    && 
  30.     left    || 
  31.     nonassoc    .. 
  32.     right    ?: 
  33.     right    = += -= *= etc. 
  34.     left    , => 
  35.     nonassoc    list operators (rightward) 
  36.     left    not 
  37.     left    and 
  38.     left    or xor 
  39. </listing>
  40. In the following sections, these operators are covered in precedence order.
  41. <p><h2>DESCRIPTIONS</h2>
  42. <h3>Terms and List Operators (Leftward)</h3>
  43. Any TERM is of highest precedence of Perl.  These includes variables,
  44. quote and quotelike operators, any expression in parentheses,
  45. and any function whose arguments are parenthesized.  Actually, there
  46. aren't really functions in this sense, just list operators and unary
  47. operators behaving as functions because you put parentheses around
  48. the arguments.  These are all documented in 
  49. <A HREF="perlfunc.html">
  50. the perlfunc manpage</A>
  51. .
  52. <p>If any list operator (print(), etc.) or any unary operator (chdir(), etc.)
  53. is followed by a left parenthesis as the next token, the operator and
  54. arguments within parentheses are taken to be of highest precedence,
  55. just like a normal function call.
  56. <p>In the absence of parentheses, the precedence of list operators such as
  57.  
  58. <A HREF="perlfunc.html#perlfunc_189">print</A>
  59. <A HREF="perlfunc.html#perlfunc_234">sort</A>
  60. , or 
  61. <A HREF="perlfunc.html#perlfunc_81">chmod</A>
  62.  is either very high or very low depending on
  63. whether you look at the left side of operator or the right side of it.
  64. For example, in
  65. <p><pre>
  66.         @ary = (1, 3, sort 4, 2);
  67.         print @ary;             # prints 1324
  68. </pre>
  69. the commas on the right of the sort are evaluated before the sort, but
  70. the commas on the left are evaluated after.  In other words, list
  71. operators tend to gobble up all the arguments that follow them, and
  72. then act like a simple TERM with regard to the preceding expression.
  73. Note that you have to be careful with parens:
  74. <p><pre>
  75.         # These evaluate exit before doing the print:
  76.         print($foo, exit);      # Obviously not what you want.
  77.         print $foo, exit;       # Nor is this.
  78. </pre>
  79. <pre>
  80.         # These do the print before evaluating exit:
  81.         (print $foo), exit;     # This is what you want.
  82.         print($foo), exit;      # Or this.
  83.         print ($foo), exit;     # Or even this.
  84. </pre>
  85. Also note that
  86. <p><pre>
  87.         print ($foo & 255) + 1, "\n";
  88. </pre>
  89. probably doesn't do what you expect at first glance.  See 
  90.  
  91. <A HREF="perlop.html#perlop_301">Named Unary Operators</A>
  92.  for more discussion of this.
  93. <p>Also parsed as terms are the <B>do {}</B> and <B>eval {}</B> constructs, as
  94. well as subroutine and method calls, and the anonymous 
  95. constructors <B>[]</B> and <B>{}</B>.
  96. <p>See also 
  97. <A HREF="perlop.html#perlop_319">Quote and Quotelike Operators</A>
  98.  toward the end of this section,
  99. as well as 
  100. <A HREF="perlop.html#perlop_329">I/O Operators</A>
  101. .
  102. <p><h3>The Arrow Operator</h3>
  103. Just as in C and C++, "<B>-></B>" is an infix dereference operator.  If the
  104. right side is either a <B>[...]</B> or <B>{...}</B> subscript, then the left side
  105. must be either a hard or symbolic reference to an array or hash (or
  106. a location capable of holding a hard reference, if it's an lvalue (assignable)).
  107. See 
  108. <A HREF="perlref.html">
  109. the perlref manpage</A>
  110. .
  111. <p>Otherwise, the right side is a method name or a simple scalar variable
  112. containing the method name, and the left side must either be an object
  113. (a blessed reference) or a class name (that is, a package name).
  114. See 
  115. <A HREF="perlobj.html">
  116. the perlobj manpage</A>
  117. .
  118. <p><h3>Autoincrement and Autodecrement</h3>
  119. "++" and "--" work as in C.  That is, if placed before a variable, they
  120. increment or decrement the variable before returning the value, and if
  121. placed after, increment or decrement the variable after returning the value.
  122. <p>The autoincrement operator has a little extra built-in magic to it.  If
  123. you increment a variable that is numeric, or that has ever been used in
  124. a numeric context, you get a normal increment.  If, however, the
  125. variable has only been used in string contexts since it was set, and
  126. has a value that is not null and matches the pattern
  127. <B>/^[a-zA-Z]*[0-9]*$/</B>, the increment is done as a string, preserving each
  128. character within its range, with carry:
  129. <p><pre>
  130.         print ++($foo = '99');  # prints '100'
  131.         print ++($foo = 'a0');  # prints 'a1'
  132.         print ++($foo = 'Az');  # prints 'Ba'
  133.         print ++($foo = 'zz');  # prints 'aaa'
  134. </pre>
  135. The autodecrement operator is not magical.
  136. <p><h3>Exponentiation</h3>
  137. Binary "**" is the exponentiation operator.  Note that it binds even more
  138. tightly than unary minus, so -2**4 is -(2**4), not (-2)**4.
  139. <p><h3>Symbolic Unary Operators</h3>
  140. Unary "!" performs logical negation, i.e. "not".  See also <B>not</B> for a lower
  141. precedence version of this.
  142. <p>Unary "-" performs arithmetic negation if the operand is numeric.  If
  143. the operand is an identifier, a string consisting of a minus sign
  144. concatenated with the identifier is returned.  Otherwise, if the string
  145. starts with a plus or minus, a string starting with the opposite sign
  146. is returned.  One effect of these rules is that <B>-bareword</B> is equivalent
  147. to <B>"-bareword"</B>.
  148. <p>Unary "~" performs bitwise negation, i.e. 1's complement.
  149. <p>Unary "+" has no effect whatsoever, even on strings.  It is useful
  150. syntactically for separating a function name from a parenthesized expression
  151. that would otherwise be interpreted as the complete list of function
  152. arguments.  (See examples above under List Operators.)
  153. <p>Unary "\" creates a reference to whatever follows it.  See 
  154. <A HREF="perlref.html">
  155. the perlref manpage</A>
  156. .
  157. Do not confuse this behavior with the behavior of backslash within a
  158. string, although both forms do convey the notion of protecting the next
  159. thing from interpretation.
  160. <p><h3>Binding Operators</h3>
  161. Binary "=~" binds an expression to a pattern match.
  162. Certain operations search or modify the string $_ by default.  This
  163. operator makes that kind of operation work on some other string.  The
  164. right argument is a search pattern, substitution, or translation.  The
  165. left argument is what is supposed to be searched, substituted, or
  166. translated instead of the default $_.  The return value indicates the
  167. success of the operation.  (If the right argument is an expression
  168. rather than a search pattern, substitution, or translation, it is
  169. interpreted as a search pattern at run time.  This is less efficient
  170. than an explicit search, since the pattern must be compiled every time
  171. the expression is evaluated--unless you've used <B>/o</B>.)
  172. <p>Binary "!~" is just like "=~" except the return value is negated in
  173. the logical sense.
  174. <p><h3>Multiplicative Operators</h3>
  175. Binary "*" multiplies two numbers.
  176. <p>Binary "/" divides two numbers.
  177. <p>Binary "%" computes the modulus of the two numbers.
  178. <p>Binary "x" is the repetition operator.  In a scalar context, it
  179. returns a string consisting of the left operand repeated the number of
  180. times specified by the right operand.  In a list context, if the left
  181. operand is a list in parens, it repeats the list.
  182. <p><pre>
  183.         print '-' x 80;         # print row of dashes
  184. </pre>
  185. <pre>
  186.         print "\t" x ($tab/8), ' ' x ($tab%8);  # tab over
  187. </pre>
  188. <pre>
  189.         @ones = (1) x 80;               # a list of 80 1's
  190.         @ones = (5) x @ones;    # set all elements to 5
  191. </pre>
  192. <h3>Additive Operators</h3>
  193. Binary "+" returns the sum of two numbers.
  194. <p>Binary "-" returns the difference of two numbers.
  195. <p>Binary "." concatenates two strings.
  196. <p><h3>Shift Operators</h3>
  197. Binary "<<" returns the value of its left argument shifted left by the
  198. number of bits specified by the right argument.  Arguments should be 
  199. integers.
  200. <p>Binary >>" returns the value of its left argument shifted right by the
  201. number of bits specified by the right argument.  Arguments should be 
  202. integers.
  203. <p><h3>Named Unary Operators</h3>
  204. The various named unary operators are treated as functions with one
  205. argument, with optional parentheses.  These include the filetest
  206. operators, like <B>-f</B>, <B>-M</B>, etc.  See 
  207. <A HREF="perlfunc.html">
  208. the perlfunc manpage</A>
  209. .
  210. <p>If any list operator (print(), etc.) or any unary operator (chdir(), etc.)
  211. is followed by a left parenthesis as the next token, the operator and
  212. arguments within parentheses are taken to be of highest precedence,
  213. just like a normal function call.  Examples:
  214. <p><pre>
  215.         chdir $foo    || die;   # (chdir $foo) || die
  216.         chdir($foo)   || die;   # (chdir $foo) || die
  217.         chdir ($foo)  || die;   # (chdir $foo) || die
  218.         chdir +($foo) || die;   # (chdir $foo) || die
  219. </pre>
  220. but, because * is higher precedence than ||:
  221. <p><pre>
  222.         chdir $foo * 20;        # chdir ($foo * 20)
  223.         chdir($foo) * 20;       # (chdir $foo) * 20
  224.         chdir ($foo) * 20;      # (chdir $foo) * 20
  225.         chdir +($foo) * 20;     # chdir ($foo * 20)
  226. </pre>
  227. <pre>
  228.         rand 10 * 20;   # rand (10 * 20)
  229.         rand(10) * 20;  # (rand 10) * 20
  230.         rand (10) * 20; # (rand 10) * 20
  231.         rand +(10) * 20;        # rand (10 * 20)
  232. </pre>
  233. See also "List Operators".
  234. <p><h3>Relational Operators</h3>
  235. Binary "<" returns true if the left argument is numerically less than
  236. the right argument.
  237. <p>Binary ">" returns true if the left argument is numerically greater
  238. than the right argument.
  239. <p>Binary "<=" returns true if the left argument is numerically less than
  240. or equal to the right argument.
  241. <p>Binary ">=" returns true if the left argument is numerically greater
  242. than or equal to the right argument.
  243. <p>Binary "lt" returns true if the left argument is stringwise less than
  244. the right argument.
  245. <p>Binary "gt" returns true if the left argument is stringwise greater
  246. than the right argument.
  247. <p>Binary "le" returns true if the left argument is stringwise less than
  248. or equal to the right argument.
  249. <p>Binary "ge" returns true if the left argument is stringwise greater
  250. than or equal to the right argument.
  251. <p><h3>Equality Operators</h3>
  252. Binary "==" returns true if the left argument is numerically equal to
  253. the right argument.
  254. <p>Binary "!=" returns true if the left argument is numerically not equal
  255. to the right argument.
  256. <p>Binary "<=>" returns -1, 0, or 1 depending on whether the left argument is numerically
  257. less than, equal to, or greater than the right argument.
  258. <p>Binary "eq" returns true if the left argument is stringwise equal to
  259. the right argument.
  260. <p>Binary "ne" returns true if the left argument is stringwise not equal
  261. to the right argument.
  262. <p>Binary "cmp" returns -1, 0, or 1 depending on whether the left argument is stringwise
  263. less than, equal to, or greater than the right argument.
  264. <p><h3>Bitwise And</h3>
  265. Binary "&" returns its operators ANDed together bit by bit.
  266. <p><h3>Bitwise Or and Exclusive Or</h3>
  267. Binary "|" returns its operators ORed together bit by bit.
  268. <p>Binary "^" returns its operators XORed together bit by bit.
  269. <p><h3>C-style Logical And</h3>
  270. Binary "&&" performs a short-circuit logical AND operation.  That is,
  271. if the left operand is false, the right operand is not even evaluated.
  272. Scalar or list context propagates down to the right operand if it
  273. is evaluated.
  274. <p><h3>C-style Logical Or</h3>
  275. Binary "||" performs a short-circuit logical OR operation.  That is,
  276. if the left operand is true, the right operand is not even evaluated.
  277. Scalar or list context propagates down to the right operand if it
  278. is evaluated.
  279. <p>The <B>||</B> and <B>&&</B> operators differ from C's in that, rather than returning
  280. 0 or 1, they return the last value evaluated.  Thus, a reasonably portable
  281. way to find out the home directory (assuming it's not "0") might be:
  282. <p><pre>
  283.         $home = $ENV{'HOME'} || $ENV{'LOGDIR'} ||
  284.         (getpwuid($<))[7] || die "You're homeless!\n";
  285. </pre>
  286. As more readable alternatives to <B>&&</B> and <B>||</B>, Perl provides "and" and
  287. "or" operators (see below).  The short-circuit behavior is identical.  The
  288. precedence of "and" and "or" is much lower, however, so that you can
  289. safely use them after a list operator without the need for
  290. parentheses:
  291. <p><pre>
  292.         unlink "alpha", "beta", "gamma"
  293.             or gripe(), next LINE;
  294. </pre>
  295. With the C-style operators that would have been written like this:
  296. <p><pre>
  297.         unlink("alpha", "beta", "gamma")
  298.             || (gripe(), next LINE);
  299. </pre>
  300. <h3>Range Operator</h3>
  301. Binary ".." is the range operator, which is really two different
  302. operators depending on the context.  In a list context, it returns an
  303. array of values counting (by ones) from the left value to the right
  304. value.  This is useful for writing <B>for (1..10)</B> loops and for doing
  305. slice operations on arrays.  Be aware that under the current implementation,
  306. a temporary array is created, so you'll burn a lot of memory if you 
  307. write something like this:
  308. <p><pre>
  309.         for (1 .. 1_000_000) {
  310.         # code
  311.         } 
  312. </pre>
  313. In a scalar context, ".." returns a boolean value.  The operator is
  314. bistable, like a flip-flop, and emulates the line-range (comma) operator
  315. of <B>sed</B>, <B>awk</B>, and various editors.  Each ".." operator maintains its
  316. own boolean state.  It is false as long as its left operand is false.
  317. Once the left operand is true, the range operator stays true until the
  318. right operand is true, <I>AFTER</I> which the range operator becomes false
  319. again.  (It doesn't become false till the next time the range operator is
  320. evaluated.  It can test the right operand and become false on the same
  321. evaluation it became true (as in <B>awk</B>), but it still returns true once.
  322. If you don't want it to test the right operand till the next evaluation
  323. (as in <B>sed</B>), use three dots ("...") instead of two.)  The right
  324. operand is not evaluated while the operator is in the "false" state, and
  325. the left operand is not evaluated while the operator is in the "true"
  326. state.  The precedence is a little lower than || and &&.  The value
  327. returned is either the null string for false, or a sequence number
  328. (beginning with 1) for true.  The sequence number is reset for each range
  329. encountered.  The final sequence number in a range has the string "E0"
  330. appended to it, which doesn't affect its numeric value, but gives you
  331. something to search for if you want to exclude the endpoint.  You can
  332. exclude the beginning point by waiting for the sequence number to be
  333. greater than 1.  If either operand of scalar ".." is a numeric literal,
  334. that operand is implicitly compared to the 
  335. <A HREF="perlvar.html#perlvar_386">$.</A>
  336.  variable, the current
  337. line number.  Examples:
  338. <p>As a scalar operator:
  339. <p><pre>
  340.         if (101 .. 200) { print; }      # print 2nd hundred lines
  341.         next line if (1 .. /^$/);       # skip header lines
  342.         s/^/> / if (/^$/ .. eof());  # quote body
  343. </pre>
  344. As a list operator:
  345. <p><pre>
  346.         for (101 .. 200) { print; }     # print $_ 100 times
  347.         @foo = @foo[$[ .. $#foo];       # an expensive no-op
  348.         @foo = @foo[$#foo-4 .. $#foo];  # slice last 5 items
  349. </pre>
  350. The range operator (in a list context) makes use of the magical
  351. autoincrement algorithm if the operaands are strings.  You
  352. can say
  353. <p><pre>
  354.         @alphabet = ('A' .. 'Z');
  355. </pre>
  356. to get all the letters of the alphabet, or
  357. <p><pre>
  358.         $hexdigit = (0 .. 9, 'a' .. 'f')[$num & 15];
  359. </pre>
  360. to get a hexadecimal digit, or
  361. <p><pre>
  362.         @z2 = ('01' .. '31');  print $z2[$mday];
  363. </pre>
  364. to get dates with leading zeros.  If the final value specified is not
  365. in the sequence that the magical increment would produce, the sequence
  366. goes until the next value would be longer than the final value
  367. specified.
  368. <p><h3>Conditional Operator</h3>
  369. Ternary "?:" is the conditional operator, just as in C.  It works much
  370. like an if-then-else.  If the argument before the ? is true, the
  371. argument before the : is returned, otherwise the argument after the :
  372. is returned.  Scalar or list context propagates downward into the 2nd
  373. or 3rd argument, whichever is selected.  The operator may be assigned
  374. to if both the 2nd and 3rd arguments are legal lvalues (meaning that you
  375. can assign to them):
  376. <p><pre>
  377.         ($a_or_b ? $a : $b) = $c;
  378. </pre>
  379. Note that this is not guaranteed to contribute to the readability of
  380. your program.
  381. <p><h3>Assigment Operators</h3>
  382. "=" is the ordinary assignment operator.
  383. <p>Assignment operators work as in C.  That is,
  384. <p><pre>
  385.         $a += 2;
  386. </pre>
  387. is equivalent to
  388. <p><pre>
  389.         $a = $a + 2;
  390. </pre>
  391. although without duplicating any side effects that dereferencing the lvalue
  392. might trigger, such as from tie().  Other assignment operators work similarly.  
  393. The following are recognized: 
  394. <p><pre>
  395.         **=    +=    *=    &=    <<=    &&=
  396.                -=    /=    |=   >>=    ||=
  397.                .=    %=    ^=
  398.                  x=
  399. </pre>
  400. Note that while these are grouped by family, they all have the precedence
  401. of assignment.
  402. <p>Unlike in C, the assignment operator produces a valid lvalue.  Modifying
  403. an assignment is equivalent to doing the assignment and then modifying
  404. the variable that was assigned to.  This is useful for modifying
  405. a copy of something, like this:
  406. <p><pre>
  407.         ($tmp = $global) =~ tr [A-Z] [a-z];
  408. </pre>
  409. Likewise,
  410. <p><pre>
  411.         ($a += 2) *= 3;
  412. </pre>
  413. is equivalent to
  414. <p><pre>
  415.         $a += 2;
  416.         $a *= 3;
  417. </pre>
  418. <h3></h3>
  419. Binary "," is the comma operator.  In a scalar context it evaluates
  420. its left argument, throws that value away, then evaluates its right
  421. argument and returns that value.  This is just like C's comma operator.
  422. <p>In a list context, it's just the list argument separator, and inserts
  423. both its arguments into the list.
  424. <p><h3>List Operators (Rightward)</h3>
  425. On the right side of a list operator, it has very low precedence,
  426. such that it controls all comma-separated expressions found there.
  427. The only operators with lower precedence are the logical operators
  428. "and", "or", and "not", which may be used to evaluate calls to list
  429. operators without the need for extra parentheses:
  430. <p><pre>
  431.         open HANDLE, "filename"
  432.         or die "Can't open: $!\n";
  433. </pre>
  434. See also discussion of list operators in List Operators (Leftward).
  435. <p><h3>Logical Not</h3>
  436. Unary "not" returns the logical negation of the expression to its right.
  437. It's the equivalent of "!" except for the very low precedence.
  438. <p><h3>Logical And</h3>
  439. Binary "and" returns the logical conjunction of the two surrounding
  440. expressions.  It's equivalent to && except for the very low
  441. precedence.  This means that it short-circuits: i.e. the right
  442. expression is evaluated only if the left expression is true.
  443. <p><h3>Logical or and Exclusive Or</h3>
  444. Binary "or" returns the logical disjunction of the two surrounding
  445. expressions.  It's equivalent to || except for the very low
  446. precedence.  This means that it short-circuits: i.e. the right
  447. expression is evaluated only if the left expression is false.
  448. <p>Binary "xor" returns the exclusive-OR of the two surrounding expressions.
  449. It cannot short circuit, of course.
  450. <p><h3>C Operators Missing From Perl</h3>
  451. Here is what C has that Perl doesn't:
  452. <p>
  453. <dl>
  454.  
  455. <dt><b><A NAME="perlop_317">unary &</A></b>
  456. <dd>
  457. Address-of operator.  (But see the "\" operator for taking a reference.)
  458. <p></dd>
  459. <dt><B>unary *</B>
  460. <dd>
  461. Dereference-address operator. (Perl's prefix dereferencing 
  462. operators are typed: $, @, %, and &.)
  463. <p></dd>
  464.  
  465. <dt><b><A NAME="perlop_318">(TYPE)</A></b>
  466. <dd>
  467. Type casting operator.  
  468. <p></dd>
  469.  
  470. </dl>
  471.  
  472. <h3>Quote and Quotelike Operators</h3>
  473. While we usually think of quotes as literal values, in Perl they
  474. function as operators, providing various kinds of interpolating and
  475. pattern matching capabilities.  Perl provides customary quote characters
  476. for these behaviors, but also provides a way for you to choose your
  477. quote character for any of them.  In the followi<h1>Error</h1>
  478. Unable to load requested item for reason: -201
  479.