home *** CD-ROM | disk | FTP | other *** search
/ Chip 2000 May / Chip_2000-05_cd1.bin / zkuste / Perl / ActivePerl-5.6.0.613.msi / 䆊䌷䈹䈙䏵-䞅䞆䞀㡆䞃䄦䠥 / _2461d159878a25ed5300080da56d6ab1 < prev    next >
Text File  |  2000-03-23  |  96KB  |  1,717 lines

  1. <HTML>
  2. <HEAD>
  3. <TITLE>perlop - Perl operators and precedence</TITLE>
  4. <LINK REL="stylesheet" HREF="../../Active.css" TYPE="text/css">
  5. <LINK REV="made" HREF="mailto:">
  6. </HEAD>
  7.  
  8. <BODY>
  9. <TABLE BORDER=0 CELLPADDING=0 CELLSPACING=0 WIDTH=100%>
  10. <TR><TD CLASS=block VALIGN=MIDDLE WIDTH=100% BGCOLOR="#cccccc">
  11. <STRONG><P CLASS=block> perlop - Perl operators and precedence</P></STRONG>
  12. </TD></TR>
  13. </TABLE>
  14.  
  15. <A NAME="__index__"></A>
  16. <!-- INDEX BEGIN -->
  17.  
  18. <UL>
  19.  
  20.     <LI><A HREF="#name">NAME</A></LI>
  21.     <LI><A HREF="#synopsis">SYNOPSIS</A></LI>
  22.     <LI><A HREF="#description">DESCRIPTION</A></LI>
  23.     <UL>
  24.  
  25.         <LI><A HREF="#terms and list operators (leftward)">Terms and List Operators (Leftward)</A></LI>
  26.         <LI><A HREF="#the arrow operator">The Arrow Operator</A></LI>
  27.         <LI><A HREF="#autoincrement and autodecrement">Auto-increment and Auto-decrement</A></LI>
  28.         <LI><A HREF="#exponentiation">Exponentiation</A></LI>
  29.         <LI><A HREF="#symbolic unary operators">Symbolic Unary Operators</A></LI>
  30.         <LI><A HREF="#binding operators">Binding Operators</A></LI>
  31.         <LI><A HREF="#multiplicative operators">Multiplicative Operators</A></LI>
  32.         <LI><A HREF="#additive operators">Additive Operators</A></LI>
  33.         <LI><A HREF="#shift operators">Shift Operators</A></LI>
  34.         <LI><A HREF="#named unary operators">Named Unary Operators</A></LI>
  35.         <LI><A HREF="#relational operators">Relational Operators</A></LI>
  36.         <LI><A HREF="#equality operators">Equality Operators</A></LI>
  37.         <LI><A HREF="#bitwise and">Bitwise And</A></LI>
  38.         <LI><A HREF="#bitwise or and exclusive or">Bitwise Or and Exclusive Or</A></LI>
  39.         <LI><A HREF="#cstyle logical and">C-style Logical And</A></LI>
  40.         <LI><A HREF="#cstyle logical or">C-style Logical Or</A></LI>
  41.         <LI><A HREF="#range operators">Range Operators</A></LI>
  42.         <LI><A HREF="#conditional operator">Conditional Operator</A></LI>
  43.         <LI><A HREF="#assignment operators">Assignment Operators</A></LI>
  44.         <LI><A HREF="#comma operator">Comma Operator</A></LI>
  45.         <LI><A HREF="#list operators (rightward)">List Operators (Rightward)</A></LI>
  46.         <LI><A HREF="#logical not">Logical Not</A></LI>
  47.         <LI><A HREF="#logical and">Logical And</A></LI>
  48.         <LI><A HREF="#logical or and exclusive or">Logical or and Exclusive Or</A></LI>
  49.         <LI><A HREF="#c operators missing from perl">C Operators Missing From Perl</A></LI>
  50.         <LI><A HREF="#quote and quotelike operators">Quote and Quote-like Operators</A></LI>
  51.         <LI><A HREF="#regexp quotelike operators">Regexp Quote-Like Operators</A></LI>
  52.         <LI><A HREF="#gory details of parsing quoted constructs">Gory details of parsing quoted constructs</A></LI>
  53.         <LI><A HREF="#i/o operators">I/O Operators</A></LI>
  54.         <LI><A HREF="#constant folding">Constant Folding</A></LI>
  55.         <LI><A HREF="#bitwise string operators">Bitwise String Operators</A></LI>
  56.         <LI><A HREF="#integer arithmetic">Integer Arithmetic</A></LI>
  57.         <LI><A HREF="#floatingpoint arithmetic">Floating-point Arithmetic</A></LI>
  58.         <LI><A HREF="#bigger numbers">Bigger Numbers</A></LI>
  59.     </UL>
  60.  
  61. </UL>
  62. <!-- INDEX END -->
  63.  
  64. <HR>
  65. <P>
  66. <H1><A NAME="name">NAME</A></H1>
  67. <P>perlop - Perl operators and precedence</P>
  68. <P>
  69. <HR>
  70. <H1><A NAME="synopsis">SYNOPSIS</A></H1>
  71. <P>Perl operators have the following associativity and precedence,
  72. listed from highest precedence to lowest.  Operators borrowed from
  73. C keep the same precedence relationship with each other, even where
  74. C's precedence is slightly screwy.  (This makes learning Perl easier
  75. for C folks.)  With very few exceptions, these all operate on scalar
  76. values only, not array values.</P>
  77. <PRE>
  78.     left        terms and list operators (leftward)
  79.     left        ->
  80.     nonassoc    ++ --
  81.     right       **
  82.     right       ! ~ \ and unary + and -
  83.     left        =~ !~
  84.     left        * / % x
  85.     left        + - .
  86.     left        << >>
  87.     nonassoc    named unary operators
  88.     nonassoc    < > <= >= lt gt le ge
  89.     nonassoc    == != <=> eq ne cmp
  90.     left        &
  91.     left        | ^
  92.     left        &&
  93.     left        ||
  94.     nonassoc    ..  ...
  95.     right       ?:
  96.     right       = += -= *= etc.
  97.     left        , =>
  98.     nonassoc    list operators (rightward)
  99.     right       not
  100.     left        and
  101.     left        or xor</PRE>
  102. <P>In the following sections, these operators are covered in precedence order.</P>
  103. <P>Many operators can be overloaded for objects.  See <A HREF="../../lib/overload.html">the overload manpage</A>.</P>
  104. <P>
  105. <HR>
  106. <H1><A NAME="description">DESCRIPTION</A></H1>
  107. <P>
  108. <H2><A NAME="terms and list operators (leftward)">Terms and List Operators (Leftward)</A></H2>
  109. <P>A TERM has the highest precedence in Perl.  They include variables,
  110. quote and quote-like operators, any expression in parentheses,
  111. and any function whose arguments are parenthesized.  Actually, there
  112. aren't really functions in this sense, just list operators and unary
  113. operators behaving as functions because you put parentheses around
  114. the arguments.  These are all documented in <A HREF="../../lib/Pod/perlfunc.html">the perlfunc manpage</A>.</P>
  115. <P>If any list operator (print(), etc.) or any unary operator (chdir(), etc.)
  116. is followed by a left parenthesis as the next token, the operator and
  117. arguments within parentheses are taken to be of highest precedence,
  118. just like a normal function call.</P>
  119. <P>In the absence of parentheses, the precedence of list operators such as
  120. <A HREF="../../lib/Pod/perlfunc.html#item_print"><CODE>print</CODE></A>, <A HREF="../../lib/Pod/perlfunc.html#item_sort"><CODE>sort</CODE></A>, or <A HREF="../../lib/Pod/perlfunc.html#item_chmod"><CODE>chmod</CODE></A> is either very high or very low depending on
  121. whether you are looking at the left side or the right side of the operator.
  122. For example, in</P>
  123. <PRE>
  124.     @ary = (1, 3, sort 4, 2);
  125.     print @ary;         # prints 1324</PRE>
  126. <P>the commas on the right of the sort are evaluated before the sort,
  127. but the commas on the left are evaluated after.  In other words,
  128. list operators tend to gobble up all arguments that follow, and
  129. then act like a simple TERM with regard to the preceding expression.
  130. Be careful with parentheses:</P>
  131. <PRE>
  132.     # These evaluate exit before doing the print:
  133.     print($foo, exit);  # Obviously not what you want.
  134.     print $foo, exit;   # Nor is this.</PRE>
  135. <PRE>
  136.     # These do the print before evaluating exit:
  137.     (print $foo), exit; # This is what you want.
  138.     print($foo), exit;  # Or this.
  139.     print ($foo), exit; # Or even this.</PRE>
  140. <P>Also note that</P>
  141. <PRE>
  142.     print ($foo & 255) + 1, "\n";</PRE>
  143. <P>probably doesn't do what you expect at first glance.  See
  144. <A HREF="#named unary operators">Named Unary Operators</A> for more discussion of this.</P>
  145. <P>Also parsed as terms are the <A HREF="../../lib/Pod/perlfunc.html#item_do"><CODE>do {}</CODE></A> and <A HREF="../../lib/Pod/perlfunc.html#item_eval"><CODE>eval {}</CODE></A> constructs, as
  146. well as subroutine and method calls, and the anonymous
  147. constructors <CODE>[]</CODE> and <CODE>{}</CODE>.</P>
  148. <P>See also <A HREF="#quote and quotelike operators">Quote and Quote-like Operators</A> toward the end of this section,
  149. as well as <A HREF="#i/o operators">I/O Operators</A>.</P>
  150. <P>
  151. <H2><A NAME="the arrow operator">The Arrow Operator</A></H2>
  152. <P>``<CODE>-></CODE>'' is an infix dereference operator, just as it is in C
  153. and C++.  If the right side is either a <CODE>[...]</CODE>, <CODE>{...}</CODE>, or a
  154. <CODE>(...)</CODE> subscript, then the left side must be either a hard or
  155. symbolic reference to an array, a hash, or a subroutine respectively.
  156. (Or technically speaking, a location capable of holding a hard
  157. reference, if it's an array or hash reference being used for
  158. assignment.)  See <A HREF="../../lib/Pod/perlreftut.html">the perlreftut manpage</A> and <A HREF="../../lib/Pod/perlref.html">the perlref manpage</A>.</P>
  159. <P>Otherwise, the right side is a method name or a simple scalar
  160. variable containing either the method name or a subroutine reference,
  161. and the left side must be either an object (a blessed reference)
  162. or a class name (that is, a package name).  See <A HREF="../../lib/Pod/perlobj.html">the perlobj manpage</A>.</P>
  163. <P>
  164. <H2><A NAME="autoincrement and autodecrement">Auto-increment and Auto-decrement</A></H2>
  165. <P>``++'' and ``--'' work as in C.  That is, if placed before a variable, they
  166. increment or decrement the variable before returning the value, and if
  167. placed after, increment or decrement the variable after returning the value.</P>
  168. <P>The auto-increment operator has a little extra builtin magic to it.  If
  169. you increment a variable that is numeric, or that has ever been used in
  170. a numeric context, you get a normal increment.  If, however, the
  171. variable has been used in only string contexts since it was set, and
  172. has a value that is not the empty string and matches the pattern
  173. <CODE>/^[a-zA-Z]*[0-9]*$/</CODE>, the increment is done as a string, preserving each
  174. character within its range, with carry:</P>
  175. <PRE>
  176.     print ++($foo = '99');      # prints '100'
  177.     print ++($foo = 'a0');      # prints 'a1'
  178.     print ++($foo = 'Az');      # prints 'Ba'
  179.     print ++($foo = 'zz');      # prints 'aaa'</PRE>
  180. <P>The auto-decrement operator is not magical.</P>
  181. <P>
  182. <H2><A NAME="exponentiation">Exponentiation</A></H2>
  183. <P>Binary ``**'' is the exponentiation operator.  It binds even more
  184. tightly than unary minus, so -2**4 is -(2**4), not (-2)**4. (This is
  185. implemented using C's <CODE>pow(3)</CODE> function, which actually works on doubles
  186. internally.)</P>
  187. <P>
  188. <H2><A NAME="symbolic unary operators">Symbolic Unary Operators</A></H2>
  189. <P>Unary ``!'' performs logical negation, i.e., ``not''.  See also <CODE>not</CODE> for a lower
  190. precedence version of this.</P>
  191. <P>Unary ``-'' performs arithmetic negation if the operand is numeric.  If
  192. the operand is an identifier, a string consisting of a minus sign
  193. concatenated with the identifier is returned.  Otherwise, if the string
  194. starts with a plus or minus, a string starting with the opposite sign
  195. is returned.  One effect of these rules is that <CODE>-bareword</CODE> is equivalent
  196. to <CODE>"-bareword"</CODE>.</P>
  197. <P>Unary ``~'' performs bitwise negation, i.e., 1's complement.  For
  198. example, <CODE>0666 & ~027</CODE> is 0640.  (See also <A HREF="#integer arithmetic">Integer Arithmetic</A> and
  199. <A HREF="#bitwise string operators">Bitwise String Operators</A>.)  Note that the width of the result is
  200. platform-dependent: ~0 is 32 bits wide on a 32-bit platform, but 64
  201. bits wide on a 64-bit platform, so if you are expecting a certain bit
  202. width, remember use the & operator to mask off the excess bits.</P>
  203. <P>Unary ``+'' has no effect whatsoever, even on strings.  It is useful
  204. syntactically for separating a function name from a parenthesized expression
  205. that would otherwise be interpreted as the complete list of function
  206. arguments.  (See examples above under <A HREF="#terms and list operators (leftward)">Terms and List Operators (Leftward)</A>.)</P>
  207. <P>Unary ``\'' creates a reference to whatever follows it.  See <A HREF="../../lib/Pod/perlreftut.html">the perlreftut manpage</A>
  208. and <A HREF="../../lib/Pod/perlref.html">the perlref manpage</A>.  Do not confuse this behavior with the behavior of
  209. backslash within a string, although both forms do convey the notion
  210. of protecting the next thing from interpolation.</P>
  211. <P>
  212. <H2><A NAME="binding operators">Binding Operators</A></H2>
  213. <P>Binary ``=~'' binds a scalar expression to a pattern match.  Certain operations
  214. search or modify the string $_ by default.  This operator makes that kind
  215. of operation work on some other string.  The right argument is a search
  216. pattern, substitution, or transliteration.  The left argument is what is
  217. supposed to be searched, substituted, or transliterated instead of the default
  218. $_.  When used in scalar context, the return value generally indicates the
  219. success of the operation.  Behavior in list context depends on the particular
  220. operator.  See <A HREF="#regexp quotelike operators">Regexp Quote-Like Operators</A> for details.</P>
  221. <P>If the right argument is an expression rather than a search pattern,
  222. substitution, or transliteration, it is interpreted as a search pattern at run
  223. time.  This can be less efficient than an explicit search, because the
  224. pattern must be compiled every time the expression is evaluated.</P>
  225. <P>Binary ``!~'' is just like ``=~'' except the return value is negated in
  226. the logical sense.</P>
  227. <P>
  228. <H2><A NAME="multiplicative operators">Multiplicative Operators</A></H2>
  229. <P>Binary ``*'' multiplies two numbers.</P>
  230. <P>Binary ``/'' divides two numbers.</P>
  231. <P>Binary ``%'' computes the modulus of two numbers.  Given integer
  232. operands <CODE>$a</CODE> and <CODE>$b</CODE>: If <CODE>$b</CODE> is positive, then <CODE>$a % $b</CODE> is
  233. <CODE>$a</CODE> minus the largest multiple of <CODE>$b</CODE> that is not greater than
  234. <CODE>$a</CODE>.  If <CODE>$b</CODE> is negative, then <CODE>$a % $b</CODE> is <CODE>$a</CODE> minus the
  235. smallest multiple of <CODE>$b</CODE> that is not less than <CODE>$a</CODE> (i.e. the
  236. result will be less than or equal to zero). 
  237. Note than when <CODE>use integer</CODE> is in scope, ``%'' give you direct access
  238. to the modulus operator as implemented by your C compiler.  This
  239. operator is not as well defined for negative operands, but it will
  240. execute faster.</P>
  241. <P>Binary ``x'' is the repetition operator.  In scalar context or if the left
  242. operand is not enclosed in parentheses, it returns a string consisting
  243. of the left operand repeated the number of times specified by the right
  244. operand.  In list context, if the left operand is enclosed in
  245. parentheses, it repeats the list.</P>
  246. <PRE>
  247.     print '-' x 80;             # print row of dashes</PRE>
  248. <PRE>
  249.     print "\t" x ($tab/8), ' ' x ($tab%8);      # tab over</PRE>
  250. <PRE>
  251.     @ones = (1) x 80;           # a list of 80 1's
  252.     @ones = (5) x @ones;        # set all elements to 5</PRE>
  253. <P>
  254. <H2><A NAME="additive operators">Additive Operators</A></H2>
  255. <P>Binary ``+'' returns the sum of two numbers.</P>
  256. <P>Binary ``-'' returns the difference of two numbers.</P>
  257. <P>Binary ``.'' concatenates two strings.</P>
  258. <P>
  259. <H2><A NAME="shift operators">Shift Operators</A></H2>
  260. <P>Binary ``<<'' returns the value of its left argument shifted left by the
  261. number of bits specified by the right argument.  Arguments should be
  262. integers.  (See also <A HREF="#integer arithmetic">Integer Arithmetic</A>.)</P>
  263. <P>Binary ``>>'' returns the value of its left argument shifted right by
  264. the number of bits specified by the right argument.  Arguments should
  265. be integers.  (See also <A HREF="#integer arithmetic">Integer Arithmetic</A>.)</P>
  266. <P>
  267. <H2><A NAME="named unary operators">Named Unary Operators</A></H2>
  268. <P>The various named unary operators are treated as functions with one
  269. argument, with optional parentheses.  These include the filetest
  270. operators, like <CODE>-f</CODE>, <CODE>-M</CODE>, etc.  See <A HREF="../../lib/Pod/perlfunc.html">the perlfunc manpage</A>.</P>
  271. <P>If any list operator (print(), etc.) or any unary operator (chdir(), etc.)
  272. is followed by a left parenthesis as the next token, the operator and
  273. arguments within parentheses are taken to be of highest precedence,
  274. just like a normal function call.  Examples:</P>
  275. <PRE>
  276.     chdir $foo    || die;       # (chdir $foo) || die
  277.     chdir($foo)   || die;       # (chdir $foo) || die
  278.     chdir ($foo)  || die;       # (chdir $foo) || die
  279.     chdir +($foo) || die;       # (chdir $foo) || die</PRE>
  280. <P>but, because * is higher precedence than ||:</P>
  281. <PRE>
  282.     chdir $foo * 20;    # chdir ($foo * 20)
  283.     chdir($foo) * 20;   # (chdir $foo) * 20
  284.     chdir ($foo) * 20;  # (chdir $foo) * 20
  285.     chdir +($foo) * 20; # chdir ($foo * 20)</PRE>
  286. <PRE>
  287.     rand 10 * 20;       # rand (10 * 20)
  288.     rand(10) * 20;      # (rand 10) * 20
  289.     rand (10) * 20;     # (rand 10) * 20
  290.     rand +(10) * 20;    # rand (10 * 20)</PRE>
  291. <P>See also <A HREF="#terms and list operators (leftward)">Terms and List Operators (Leftward)</A>.</P>
  292. <P>
  293. <H2><A NAME="relational operators">Relational Operators</A></H2>
  294. <P>Binary ``<'' returns true if the left argument is numerically less than
  295. the right argument.</P>
  296. <P>Binary ``>'' returns true if the left argument is numerically greater
  297. than the right argument.</P>
  298. <P>Binary ``<='' returns true if the left argument is numerically less than
  299. or equal to the right argument.</P>
  300. <P>Binary ``>='' returns true if the left argument is numerically greater
  301. than or equal to the right argument.</P>
  302. <P>Binary ``lt'' returns true if the left argument is stringwise less than
  303. the right argument.</P>
  304. <P>Binary ``gt'' returns true if the left argument is stringwise greater
  305. than the right argument.</P>
  306. <P>Binary ``le'' returns true if the left argument is stringwise less than
  307. or equal to the right argument.</P>
  308. <P>Binary ``ge'' returns true if the left argument is stringwise greater
  309. than or equal to the right argument.</P>
  310. <P>
  311. <H2><A NAME="equality operators">Equality Operators</A></H2>
  312. <P>Binary ``=='' returns true if the left argument is numerically equal to
  313. the right argument.</P>
  314. <P>Binary ``!='' returns true if the left argument is numerically not equal
  315. to the right argument.</P>
  316. <P>Binary ``<=>'' returns -1, 0, or 1 depending on whether the left
  317. argument is numerically less than, equal to, or greater than the right
  318. argument.</P>
  319. <P>Binary ``eq'' returns true if the left argument is stringwise equal to
  320. the right argument.</P>
  321. <P>Binary ``ne'' returns true if the left argument is stringwise not equal
  322. to the right argument.</P>
  323. <P>Binary ``cmp'' returns -1, 0, or 1 depending on whether the left argument is stringwise
  324. less than, equal to, or greater than the right argument.</P>
  325. <P>``lt'', ``le'', ``ge'', ``gt'' and ``cmp'' use the collation (sort) order specified
  326. by the current locale if <CODE>use locale</CODE> is in effect.  See <A HREF="../../lib/Pod/perllocale.html">the perllocale manpage</A>.</P>
  327. <P>
  328. <H2><A NAME="bitwise and">Bitwise And</A></H2>
  329. <P>Binary ``&'' returns its operators ANDed together bit by bit.
  330. (See also <A HREF="#integer arithmetic">Integer Arithmetic</A> and <A HREF="#bitwise string operators">Bitwise String Operators</A>.)</P>
  331. <P>
  332. <H2><A NAME="bitwise or and exclusive or">Bitwise Or and Exclusive Or</A></H2>
  333. <P>Binary ``|'' returns its operators ORed together bit by bit.
  334. (See also <A HREF="#integer arithmetic">Integer Arithmetic</A> and <A HREF="#bitwise string operators">Bitwise String Operators</A>.)</P>
  335. <P>Binary ``^'' returns its operators XORed together bit by bit.
  336. (See also <A HREF="#integer arithmetic">Integer Arithmetic</A> and <A HREF="#bitwise string operators">Bitwise String Operators</A>.)</P>
  337. <P>
  338. <H2><A NAME="cstyle logical and">C-style Logical And</A></H2>
  339. <P>Binary ``&&'' performs a short-circuit logical AND operation.  That is,
  340. if the left operand is false, the right operand is not even evaluated.
  341. Scalar or list context propagates down to the right operand if it
  342. is evaluated.</P>
  343. <P>
  344. <H2><A NAME="cstyle logical or">C-style Logical Or</A></H2>
  345. <P>Binary ``||'' performs a short-circuit logical OR operation.  That is,
  346. if the left operand is true, the right operand is not even evaluated.
  347. Scalar or list context propagates down to the right operand if it
  348. is evaluated.</P>
  349. <P>The <CODE>||</CODE> and <CODE>&&</CODE> operators differ from C's in that, rather than returning
  350. 0 or 1, they return the last value evaluated.  Thus, a reasonably portable
  351. way to find out the home directory (assuming it's not ``0'') might be:</P>
  352. <PRE>
  353.     $home = $ENV{'HOME'} || $ENV{'LOGDIR'} ||
  354.         (getpwuid($<))[7] || die "You're homeless!\n";</PRE>
  355. <P>In particular, this means that you shouldn't use this
  356. for selecting between two aggregates for assignment:</P>
  357. <PRE>
  358.     @a = @b || @c;              # this is wrong
  359.     @a = scalar(@b) || @c;      # really meant this
  360.     @a = @b ? @b : @c;          # this works fine, though</PRE>
  361. <P>As more readable alternatives to <CODE>&&</CODE> and <CODE>||</CODE> when used for
  362. control flow, Perl provides <CODE>and</CODE> and <CODE>or</CODE> operators (see below).
  363. The short-circuit behavior is identical.  The precedence of ``and'' and
  364. ``or'' is much lower, however, so that you can safely use them after a
  365. list operator without the need for parentheses:</P>
  366. <PRE>
  367.     unlink "alpha", "beta", "gamma"
  368.             or gripe(), next LINE;</PRE>
  369. <P>With the C-style operators that would have been written like this:</P>
  370. <PRE>
  371.     unlink("alpha", "beta", "gamma")
  372.             || (gripe(), next LINE);</PRE>
  373. <P>Using ``or'' for assignment is unlikely to do what you want; see below.</P>
  374. <P>
  375. <H2><A NAME="range operators">Range Operators</A></H2>
  376. <P>Binary ``..'' is the range operator, which is really two different
  377. operators depending on the context.  In list context, it returns an
  378. array of values counting (up by ones) from the left value to the right
  379. value.  If the left value is greater than the right value then it
  380. returns the empty array.  The range operator is useful for writing
  381. <CODE>foreach (1..10)</CODE> loops and for doing slice operations on arrays.  In
  382. the current implementation, no temporary array is created when the
  383. range operator is used as the expression in <CODE>foreach</CODE> loops, but older
  384. versions of Perl might burn a lot of memory when you write something
  385. like this:</P>
  386. <PRE>
  387.     for (1 .. 1_000_000) {
  388.         # code
  389.     }</PRE>
  390. <P>In scalar context, ``..'' returns a boolean value.  The operator is
  391. bistable, like a flip-flop, and emulates the line-range (comma) operator
  392. of <STRONG>sed</STRONG>, <STRONG>awk</STRONG>, and various editors.  Each ``..'' operator maintains its
  393. own boolean state.  It is false as long as its left operand is false.
  394. Once the left operand is true, the range operator stays true until the
  395. right operand is true, <EM>AFTER</EM> which the range operator becomes false
  396. again.  It doesn't become false till the next time the range operator is
  397. evaluated.  It can test the right operand and become false on the same
  398. evaluation it became true (as in <STRONG>awk</STRONG>), but it still returns true once.
  399. If you don't want it to test the right operand till the next
  400. evaluation, as in <STRONG>sed</STRONG>, just use three dots (``...'') instead of
  401. two.  In all other regards, ``...'' behaves just like ``..'' does.</P>
  402. <P>The right operand is not evaluated while the operator is in the
  403. ``false'' state, and the left operand is not evaluated while the
  404. operator is in the ``true'' state.  The precedence is a little lower
  405. than || and &&.  The value returned is either the empty string for
  406. false, or a sequence number (beginning with 1) for true.  The
  407. sequence number is reset for each range encountered.  The final
  408. sequence number in a range has the string ``E0'' appended to it, which
  409. doesn't affect its numeric value, but gives you something to search
  410. for if you want to exclude the endpoint.  You can exclude the
  411. beginning point by waiting for the sequence number to be greater
  412. than 1.  If either operand of scalar ``..'' is a constant expression,
  413. that operand is implicitly compared to the <CODE>$.</CODE> variable, the
  414. current line number.  Examples:</P>
  415. <P>As a scalar operator:</P>
  416. <PRE>
  417.     if (101 .. 200) { print; }  # print 2nd hundred lines
  418.     next line if (1 .. /^$/);   # skip header lines
  419.     s/^/> / if (/^$/ .. eof()); # quote body</PRE>
  420. <PRE>
  421.     # parse mail messages
  422.     while (<>) {
  423.         $in_header =   1  .. /^$/;
  424.         $in_body   = /^$/ .. eof();
  425.         # do something based on those
  426.     } continue {
  427.         close ARGV if eof;              # reset $. each file
  428.     }</PRE>
  429. <P>As a list operator:</P>
  430. <PRE>
  431.     for (101 .. 200) { print; } # print $_ 100 times
  432.     @foo = @foo[0 .. $#foo];    # an expensive no-op
  433.     @foo = @foo[$#foo-4 .. $#foo];      # slice last 5 items</PRE>
  434. <P>The range operator (in list context) makes use of the magical
  435. auto-increment algorithm if the operands are strings.  You
  436. can say</P>
  437. <PRE>
  438.     @alphabet = ('A' .. 'Z');</PRE>
  439. <P>to get all normal letters of the alphabet, or</P>
  440. <PRE>
  441.     $hexdigit = (0 .. 9, 'a' .. 'f')[$num & 15];</PRE>
  442. <P>to get a hexadecimal digit, or</P>
  443. <PRE>
  444.     @z2 = ('01' .. '31');  print $z2[$mday];</PRE>
  445. <P>to get dates with leading zeros.  If the final value specified is not
  446. in the sequence that the magical increment would produce, the sequence
  447. goes until the next value would be longer than the final value
  448. specified.</P>
  449. <P>
  450. <H2><A NAME="conditional operator">Conditional Operator</A></H2>
  451. <P>Ternary ``?:'' is the conditional operator, just as in C.  It works much
  452. like an if-then-else.  If the argument before the ? is true, the
  453. argument before the : is returned, otherwise the argument after the :
  454. is returned.  For example:</P>
  455. <PRE>
  456.     printf "I have %d dog%s.\n", $n,
  457.             ($n == 1) ? '' : "s";</PRE>
  458. <P>Scalar or list context propagates downward into the 2nd
  459. or 3rd argument, whichever is selected.</P>
  460. <PRE>
  461.     $a = $ok ? $b : $c;  # get a scalar
  462.     @a = $ok ? @b : @c;  # get an array
  463.     $a = $ok ? @b : @c;  # oops, that's just a count!</PRE>
  464. <P>The operator may be assigned to if both the 2nd and 3rd arguments are
  465. legal lvalues (meaning that you can assign to them):</P>
  466. <PRE>
  467.     ($a_or_b ? $a : $b) = $c;</PRE>
  468. <P>Because this operator produces an assignable result, using assignments
  469. without parentheses will get you in trouble.  For example, this:</P>
  470. <PRE>
  471.     $a % 2 ? $a += 10 : $a += 2</PRE>
  472. <P>Really means this:</P>
  473. <PRE>
  474.     (($a % 2) ? ($a += 10) : $a) += 2</PRE>
  475. <P>Rather than this:</P>
  476. <PRE>
  477.     ($a % 2) ? ($a += 10) : ($a += 2)</PRE>
  478. <P>That should probably be written more simply as:</P>
  479. <PRE>
  480.     $a += ($a % 2) ? 10 : 2;</PRE>
  481. <P>
  482. <H2><A NAME="assignment operators">Assignment Operators</A></H2>
  483. <P>``='' is the ordinary assignment operator.</P>
  484. <P>Assignment operators work as in C.  That is,</P>
  485. <PRE>
  486.     $a += 2;</PRE>
  487. <P>is equivalent to</P>
  488. <PRE>
  489.     $a = $a + 2;</PRE>
  490. <P>although without duplicating any side effects that dereferencing the lvalue
  491. might trigger, such as from tie().  Other assignment operators work similarly.
  492. The following are recognized:</P>
  493. <PRE>
  494.     **=    +=    *=    &=    <<=    &&=
  495.            -=    /=    |=    >>=    ||=
  496.            .=    %=    ^=
  497.                  x=</PRE>
  498. <P>Although these are grouped by family, they all have the precedence
  499. of assignment.</P>
  500. <P>Unlike in C, the scalar assignment operator produces a valid lvalue.
  501. Modifying an assignment is equivalent to doing the assignment and
  502. then modifying the variable that was assigned to.  This is useful
  503. for modifying a copy of something, like this:</P>
  504. <PRE>
  505.     ($tmp = $global) =~ tr [A-Z] [a-z];</PRE>
  506. <P>Likewise,</P>
  507. <PRE>
  508.     ($a += 2) *= 3;</PRE>
  509. <P>is equivalent to</P>
  510. <PRE>
  511.     $a += 2;
  512.     $a *= 3;</PRE>
  513. <P>Similarly, a list assignment in list context produces the list of
  514. lvalues assigned to, and a list assignment in scalar context returns
  515. the number of elements produced by the expression on the right hand
  516. side of the assignment.</P>
  517. <P>
  518. <H2><A NAME="comma operator">Comma Operator</A></H2>
  519. <P>Binary ``,'' is the comma operator.  In scalar context it evaluates
  520. its left argument, throws that value away, then evaluates its right
  521. argument and returns that value.  This is just like C's comma operator.</P>
  522. <P>In list context, it's just the list argument separator, and inserts
  523. both its arguments into the list.</P>
  524. <P>The => digraph is mostly just a synonym for the comma operator.  It's useful for
  525. documenting arguments that come in pairs.  As of release 5.001, it also forces
  526. any word to the left of it to be interpreted as a string.</P>
  527. <P>
  528. <H2><A NAME="list operators (rightward)">List Operators (Rightward)</A></H2>
  529. <P>On the right side of a list operator, it has very low precedence,
  530. such that it controls all comma-separated expressions found there.
  531. The only operators with lower precedence are the logical operators
  532. ``and'', ``or'', and ``not'', which may be used to evaluate calls to list
  533. operators without the need for extra parentheses:</P>
  534. <PRE>
  535.     open HANDLE, "filename"
  536.         or die "Can't open: $!\n";</PRE>
  537. <P>See also discussion of list operators in <A HREF="#terms and list operators (leftward)">Terms and List Operators (Leftward)</A>.</P>
  538. <P>
  539. <H2><A NAME="logical not">Logical Not</A></H2>
  540. <P>Unary ``not'' returns the logical negation of the expression to its right.
  541. It's the equivalent of ``!'' except for the very low precedence.</P>
  542. <P>
  543. <H2><A NAME="logical and">Logical And</A></H2>
  544. <P>Binary ``and'' returns the logical conjunction of the two surrounding
  545. expressions.  It's equivalent to && except for the very low
  546. precedence.  This means that it short-circuits: i.e., the right
  547. expression is evaluated only if the left expression is true.</P>
  548. <P>
  549. <H2><A NAME="logical or and exclusive or">Logical or and Exclusive Or</A></H2>
  550. <P>Binary ``or'' returns the logical disjunction of the two surrounding
  551. expressions.  It's equivalent to || except for the very low precedence.
  552. This makes it useful for control flow</P>
  553. <PRE>
  554.     print FH $data              or die "Can't write to FH: $!";</PRE>
  555. <P>This means that it short-circuits: i.e., the right expression is evaluated
  556. only if the left expression is false.  Due to its precedence, you should
  557. probably avoid using this for assignment, only for control flow.</P>
  558. <PRE>
  559.     $a = $b or $c;              # bug: this is wrong
  560.     ($a = $b) or $c;            # really means this
  561.     $a = $b || $c;              # better written this way</PRE>
  562. <P>However, when it's a list-context assignment and you're trying to use
  563. ``||'' for control flow, you probably need ``or'' so that the assignment
  564. takes higher precedence.</P>
  565. <PRE>
  566.     @info = stat($file) || die;     # oops, scalar sense of stat!
  567.     @info = stat($file) or die;     # better, now @info gets its due</PRE>
  568. <P>Then again, you could always use parentheses.</P>
  569. <P>Binary ``xor'' returns the exclusive-OR of the two surrounding expressions.
  570. It cannot short circuit, of course.</P>
  571. <P>
  572. <H2><A NAME="c operators missing from perl">C Operators Missing From Perl</A></H2>
  573. <P>Here is what C has that Perl doesn't:</P>
  574. <DL>
  575. <DT><STRONG><A NAME="item_unary">unary &</A></STRONG><BR>
  576. <DD>
  577. Address-of operator.  (But see the ``\'' operator for taking a reference.)
  578. <P></P>
  579. <DT><STRONG><A NAME="item_unary_%2A">unary *</A></STRONG><BR>
  580. <DD>
  581. Dereference-address operator. (Perl's prefix dereferencing
  582. operators are typed: $, @, %, and &.)
  583. <P></P>
  584. <DT><STRONG><A NAME="item_%28TYPE%29">(TYPE)</A></STRONG><BR>
  585. <DD>
  586. Type-casting operator.
  587. <P></P></DL>
  588. <P>
  589. <H2><A NAME="quote and quotelike operators">Quote and Quote-like Operators</A></H2>
  590. <P>While we usually think of quotes as literal values, in Perl they
  591. function as operators, providing various kinds of interpolating and
  592. pattern matching capabilities.  Perl provides customary quote characters
  593. for these behaviors, but also provides a way for you to choose your
  594. quote character for any of them.  In the following table, a <CODE>{}</CODE> represents
  595. any pair of delimiters you choose.</P>
  596. <PRE>
  597.     Customary  Generic        Meaning        Interpolates
  598.         ''       q{}          Literal             no
  599.         ""      qq{}          Literal             yes
  600.         ``      qx{}          Command             yes (unless '' is delimiter)
  601.                 qw{}         Word list            no
  602.         //       m{}       Pattern match          yes (unless '' is delimiter)
  603.                 qr{}          Pattern             yes (unless '' is delimiter)
  604.                  s{}{}      Substitution          yes (unless '' is delimiter)
  605.                 tr{}{}    Transliteration         no (but see below)</PRE>
  606. <P>Non-bracketing delimiters use the same character fore and aft, but the four
  607. sorts of brackets (round, angle, square, curly) will all nest, which means
  608. that</P>
  609. <PRE>
  610.         q{foo{bar}baz}</PRE>
  611. <P>is the same as</P>
  612. <PRE>
  613.         'foo{bar}baz'</PRE>
  614. <P>Note, however, that this does not always work for quoting Perl code:</P>
  615. <PRE>
  616.         $s = q{ if($a eq "}") ... }; # WRONG</PRE>
  617. <P>is a syntax error. The <CODE>Text::Balanced</CODE> module on CPAN is able to do this
  618. properly.</P>
  619. <P>There can be whitespace between the operator and the quoting
  620. characters, except when <CODE>#</CODE> is being used as the quoting character.
  621. <CODE>q#foo#</CODE> is parsed as the string <CODE>foo</CODE>, while <CODE>q #foo#</CODE> is the
  622. operator <A HREF="../../lib/Pod/perlfunc.html#item_q"><CODE>q</CODE></A> followed by a comment.  Its argument will be taken
  623. from the next line.  This allows you to write:</P>
  624. <PRE>
  625.     s {foo}  # Replace foo
  626.       {bar}  # with bar.</PRE>
  627. <P>For constructs that do interpolate, variables beginning with ``<CODE>$</CODE>''
  628. or ``<CODE>@</CODE>'' are interpolated, as are the following escape sequences.  Within
  629. a transliteration, the first eleven of these sequences may be used.</P>
  630. <PRE>
  631.     \t          tab             (HT, TAB)
  632.     \n          newline         (NL)
  633.     \r          return          (CR)
  634.     \f          form feed       (FF)
  635.     \b          backspace       (BS)
  636.     \a          alarm (bell)    (BEL)
  637.     \e          escape          (ESC)
  638.     \033        octal char      (ESC)
  639.     \x1b        hex char        (ESC)
  640.     \x{263a}    wide hex char   (SMILEY)
  641.     \c[         control char    (ESC)
  642.     \N{name}    named char</PRE>
  643. <PRE>
  644.     \l          lowercase next char
  645.     \u          uppercase next char
  646.     \L          lowercase till \E
  647.     \U          uppercase till \E
  648.     \E          end case modification
  649.     \Q          quote non-word characters till \E</PRE>
  650. <P>If <CODE>use locale</CODE> is in effect, the case map used by <CODE>\l</CODE>, <CODE>\L</CODE>, <CODE>\u</CODE>
  651. and <CODE>\U</CODE> is taken from the current locale.  See <A HREF="../../lib/Pod/perllocale.html">the perllocale manpage</A>.  For
  652. documentation of <CODE>\N{name}</CODE>, see <A HREF="../../lib/charnames.html">the charnames manpage</A>.</P>
  653. <P>All systems use the virtual <CODE>"\n"</CODE> to represent a line terminator,
  654. called a ``newline''.  There is no such thing as an unvarying, physical
  655. newline character.  It is only an illusion that the operating system,
  656. device drivers, C libraries, and Perl all conspire to preserve.  Not all
  657. systems read <CODE>"\r"</CODE> as ASCII CR and <CODE>"\n"</CODE> as ASCII LF.  For example,
  658. on a Mac, these are reversed, and on systems without line terminator,
  659. printing <CODE>"\n"</CODE> may emit no actual data.  In general, use <CODE>"\n"</CODE> when
  660. you mean a ``newline'' for your system, but use the literal ASCII when you
  661. need an exact character.  For example, most networking protocols expect
  662. and prefer a CR+LF (<CODE>"\012\015"</CODE> or <CODE>"\cJ\cM"</CODE>) for line terminators,
  663. and although they often accept just <CODE>"\012"</CODE>, they seldom tolerate just
  664. <CODE>"\015"</CODE>.  If you get in the habit of using <CODE>"\n"</CODE> for networking,
  665. you may be burned some day.</P>
  666. <P>You cannot include a literal <CODE>$</CODE> or <CODE>@</CODE> within a <CODE>\Q</CODE> sequence. 
  667. An unescaped <CODE>$</CODE> or <CODE>@</CODE> interpolates the corresponding variable, 
  668. while escaping will cause the literal string <CODE>\$</CODE> to be inserted.
  669. You'll need to write something like <A HREF="#item_m/"><CODE>m/\Quser\E\@\Qhost/</CODE></A>.</P>
  670. <P>Patterns are subject to an additional level of interpretation as a
  671. regular expression.  This is done as a second pass, after variables are
  672. interpolated, so that regular expressions may be incorporated into the
  673. pattern from the variables.  If this is not what you want, use <CODE>\Q</CODE> to
  674. interpolate a variable literally.</P>
  675. <P>Apart from the behavior described above, Perl does not expand
  676. multiple levels of interpolation.  In particular, contrary to the
  677. expectations of shell programmers, back-quotes do <EM>NOT</EM> interpolate
  678. within double quotes, nor do single quotes impede evaluation of
  679. variables when used within double quotes.</P>
  680. <P>
  681. <H2><A NAME="regexp quotelike operators">Regexp Quote-Like Operators</A></H2>
  682. <P>Here are the quote-like operators that apply to pattern
  683. matching and related activities.</P>
  684. <DL>
  685. <DT><STRONG><A NAME="item_%3FPATTERN%3F">?PATTERN?</A></STRONG><BR>
  686. <DD>
  687. This is just like the <CODE>/pattern/</CODE> search, except that it matches only
  688. once between calls to the <A HREF="../../lib/Pod/perlfunc.html#item_reset"><CODE>reset()</CODE></A> operator.  This is a useful
  689. optimization when you want to see only the first occurrence of
  690. something in each file of a set of files, for instance.  Only <CODE>??</CODE>
  691. patterns local to the current package are reset.
  692. <PRE>
  693.     while (<>) {
  694.         if (?^$?) {
  695.                             # blank line between header and body
  696.         }
  697.     } continue {
  698.         reset if eof;       # clear ?? status for next file
  699.     }</PRE>
  700. <P>This usage is vaguely depreciated, which means it just might possibly
  701. be removed in some distant future version of Perl, perhaps somewhere
  702. around the year 2168.</P>
  703. <P></P>
  704. <DT><STRONG><A NAME="item_m/">m/PATTERN/cgimosx</A></STRONG><BR>
  705. <DD>
  706. <DT><STRONG><A NAME="item_%2FPATTERN%2Fcgimosx">/PATTERN/cgimosx</A></STRONG><BR>
  707. <DD>
  708. Searches a string for a pattern match, and in scalar context returns
  709. true if it succeeds, false if it fails.  If no string is specified
  710. via the <CODE>=~</CODE> or <CODE>!~</CODE> operator, the $_ string is searched.  (The
  711. string specified with <CODE>=~</CODE> need not be an lvalue--it may be the
  712. result of an expression evaluation, but remember the <CODE>=~</CODE> binds
  713. rather tightly.)  See also <A HREF="../../lib/Pod/perlre.html">the perlre manpage</A>.  See <A HREF="../../lib/Pod/perllocale.html">the perllocale manpage</A> for
  714. discussion of additional considerations that apply when <CODE>use locale</CODE>
  715. is in effect.
  716. <P>Options are:</P>
  717. <PRE>
  718.     c   Do not reset search position on a failed match when /g is in effect.
  719.     g   Match globally, i.e., find all occurrences.
  720.     i   Do case-insensitive pattern matching.
  721.     m   Treat string as multiple lines.
  722.     o   Compile pattern only once.
  723.     s   Treat string as single line.
  724.     x   Use extended regular expressions.</PRE>
  725. <P>If ``/'' is the delimiter then the initial <A HREF="../../lib/Pod/perlfunc.html#item_m"><CODE>m</CODE></A> is optional.  With the <A HREF="../../lib/Pod/perlfunc.html#item_m"><CODE>m</CODE></A>
  726. you can use any pair of non-alphanumeric, non-whitespace characters 
  727. as delimiters.  This is particularly useful for matching path names
  728. that contain ``/'', to avoid LTS (leaning toothpick syndrome).  If ``?'' is
  729. the delimiter, then the match-only-once rule of <A HREF="#item_%3FPATTERN%3F"><CODE>?PATTERN?</CODE></A> applies.
  730. If ``''' is the delimiter, no interpolation is performed on the PATTERN.</P>
  731. <P>PATTERN may contain variables, which will be interpolated (and the
  732. pattern recompiled) every time the pattern search is evaluated, except
  733. for when the delimiter is a single quote.  (Note that <CODE>$)</CODE> and <CODE>$|</CODE>
  734. might not be interpolated because they look like end-of-string tests.)
  735. If you want such a pattern to be compiled only once, add a <CODE>/o</CODE> after
  736. the trailing delimiter.  This avoids expensive run-time recompilations,
  737. and is useful when the value you are interpolating won't change over
  738. the life of the script.  However, mentioning <CODE>/o</CODE> constitutes a promise
  739. that you won't change the variables in the pattern.  If you change them,
  740. Perl won't even notice.  See also <A HREF="#qr//">qr//</A>.</P>
  741. <P>If the PATTERN evaluates to the empty string, the last
  742. <EM>successfully</EM> matched regular expression is used instead.</P>
  743. <P>If the <CODE>/g</CODE> option is not used, <A HREF="#item_m/"><CODE>m//</CODE></A> in list context returns a
  744. list consisting of the subexpressions matched by the parentheses in the
  745. pattern, i.e., (<CODE>$1</CODE>, <CODE>$2</CODE>, <CODE>$3</CODE>...).  (Note that here <CODE>$1</CODE> etc. are
  746. also set, and that this differs from Perl 4's behavior.)  When there are
  747. no parentheses in the pattern, the return value is the list <CODE>(1)</CODE> for
  748. success.  With or without parentheses, an empty list is returned upon
  749. failure.</P>
  750. <P>Examples:</P>
  751. <PRE>
  752.     open(TTY, '/dev/tty');
  753.     <TTY> =~ /^y/i && foo();    # do foo if desired</PRE>
  754. <PRE>
  755.     if (/Version: *([0-9.]*)/) { $version = $1; }</PRE>
  756. <PRE>
  757.     next if m#^/usr/spool/uucp#;</PRE>
  758. <PRE>
  759.     # poor man's grep
  760.     $arg = shift;
  761.     while (<>) {
  762.         print if /$arg/o;       # compile only once
  763.     }</PRE>
  764. <PRE>
  765.     if (($F1, $F2, $Etc) = ($foo =~ /^(\S+)\s+(\S+)\s*(.*)/))</PRE>
  766. <P>This last example splits $foo into the first two words and the
  767. remainder of the line, and assigns those three fields to $F1, $F2, and
  768. $Etc.  The conditional is true if any variables were assigned, i.e., if
  769. the pattern matched.</P>
  770. <P>The <CODE>/g</CODE> modifier specifies global pattern matching--that is,
  771. matching as many times as possible within the string.  How it behaves
  772. depends on the context.  In list context, it returns a list of the
  773. substrings matched by any capturing parentheses in the regular
  774. expression.  If there are no parentheses, it returns a list of all
  775. the matched strings, as if there were parentheses around the whole
  776. pattern.</P>
  777. <P>In scalar context, each execution of <A HREF="#item_m/"><CODE>m//g</CODE></A> finds the next match,
  778. returning true if it matches, and false if there is no further match.
  779. The position after the last match can be read or set using the <A HREF="../../lib/Pod/perlfunc.html#item_pos"><CODE>pos()</CODE></A>
  780. function; see <A HREF="../../lib/Pod/perlfunc.html#pos">pos in the perlfunc manpage</A>.   A failed match normally resets the
  781. search position to the beginning of the string, but you can avoid that
  782. by adding the <CODE>/c</CODE> modifier (e.g. <A HREF="#item_m/"><CODE>m//gc</CODE></A>).  Modifying the target
  783. string also resets the search position.</P>
  784. <P>You can intermix <A HREF="#item_m/"><CODE>m//g</CODE></A> matches with <A HREF="#item_m/"><CODE>m/\G.../g</CODE></A>, where <CODE>\G</CODE> is a
  785. zero-width assertion that matches the exact position where the previous
  786. <A HREF="#item_m/"><CODE>m//g</CODE></A>, if any, left off.  The <CODE>\G</CODE> assertion is not supported without
  787. the <CODE>/g</CODE> modifier.  (Currently, without <CODE>/g</CODE>, <CODE>\G</CODE> behaves just like
  788. <CODE>\A</CODE>, but that's accidental and may change in the future.)</P>
  789. <P>Examples:</P>
  790. <PRE>
  791.     # list context
  792.     ($one,$five,$fifteen) = (`uptime` =~ /(\d+\.\d+)/g);</PRE>
  793. <PRE>
  794.     # scalar context
  795.     $/ = ""; $* = 1;  # $* deprecated in modern perls
  796.     while (defined($paragraph = <>)) {
  797.         while ($paragraph =~ /[a-z]['")]*[.!?]+['")]*\s/g) {
  798.             $sentences++;
  799.         }
  800.     }
  801.     print "$sentences\n";</PRE>
  802. <PRE>
  803.     # using m//gc with \G
  804.     $_ = "ppooqppqq";
  805.     while ($i++ < 2) {
  806.         print "1: '";
  807.         print $1 while /(o)/gc; print "', pos=", pos, "\n";
  808.         print "2: '";
  809.         print $1 if /\G(q)/gc;  print "', pos=", pos, "\n";
  810.         print "3: '";
  811.         print $1 while /(p)/gc; print "', pos=", pos, "\n";
  812.     }</PRE>
  813. <P>The last example should print:</P>
  814. <PRE>
  815.     1: 'oo', pos=4
  816.     2: 'q', pos=5
  817.     3: 'pp', pos=7
  818.     1: '', pos=7
  819.     2: 'q', pos=8
  820.     3: '', pos=8</PRE>
  821. <P>A useful idiom for <CODE>lex</CODE>-like scanners is <CODE>/\G.../gc</CODE>.  You can
  822. combine several regexps like this to process a string part-by-part,
  823. doing different actions depending on which regexp matched.  Each
  824. regexp tries to match where the previous one leaves off.</P>
  825. <PRE>
  826.  $_ = <<'EOL';
  827.       $url = new URI::URL "<A HREF="http://www/"">http://www/"</A>;;   die if $url eq "xXx";
  828.  EOL
  829.  LOOP:
  830.     {
  831.       print(" digits"),         redo LOOP if /\G\d+\b[,.;]?\s*/gc;
  832.       print(" lowercase"),      redo LOOP if /\G[a-z]+\b[,.;]?\s*/gc;
  833.       print(" UPPERCASE"),      redo LOOP if /\G[A-Z]+\b[,.;]?\s*/gc;
  834.       print(" Capitalized"),    redo LOOP if /\G[A-Z][a-z]+\b[,.;]?\s*/gc;
  835.       print(" MiXeD"),          redo LOOP if /\G[A-Za-z]+\b[,.;]?\s*/gc;
  836.       print(" alphanumeric"),   redo LOOP if /\G[A-Za-z0-9]+\b[,.;]?\s*/gc;
  837.       print(" line-noise"),     redo LOOP if /\G[^A-Za-z0-9]+/gc;
  838.       print ". That's all!\n";
  839.     }</PRE>
  840. <P>Here is the output (split into several lines):</P>
  841. <PRE>
  842.  line-noise lowercase line-noise lowercase UPPERCASE line-noise
  843.  UPPERCASE line-noise lowercase line-noise lowercase line-noise
  844.  lowercase lowercase line-noise lowercase lowercase line-noise
  845.  MiXeD line-noise. That's all!</PRE>
  846. <P></P>
  847. <DT><STRONG><A NAME="item_q/">q/STRING/</A></STRONG><BR>
  848. <DD>
  849. <DT><STRONG><A NAME="item_%27STRING%27"><CODE>'STRING'</CODE></A></STRONG><BR>
  850. <DD>
  851. A single-quoted, literal string.  A backslash represents a backslash
  852. unless followed by the delimiter or another backslash, in which case
  853. the delimiter or backslash is interpolated.
  854. <PRE>
  855.     $foo = q!I said, "You said, 'She said it.'"!;
  856.     $bar = q('This is it.');
  857.     $baz = '\n';                # a two-character string</PRE>
  858. <P></P>
  859. <DT><STRONG><A NAME="item_qq/">qq/STRING/</A></STRONG><BR>
  860. <DD>
  861. <DT><STRONG><A NAME="item_%22STRING%22">``STRING''</A></STRONG><BR>
  862. <DD>
  863. A double-quoted, interpolated string.
  864. <PRE>
  865.     $_ .= qq
  866.      (*** The previous line contains the naughty word "$1".\n)
  867.                 if /\b(tcl|java|python)\b/i;      # :-)
  868.     $baz = "\n";                # a one-character string</PRE>
  869. <P></P>
  870. <DT><STRONG><A NAME="item_qr/">qr/STRING/imosx</A></STRONG><BR>
  871. <DD>
  872. This operators quotes--and compiles--its <EM>STRING</EM> as a regular
  873. expression.  <EM>STRING</EM> is interpolated the same way as <EM>PATTERN</EM>
  874. in <A HREF="#item_m/"><CODE>m/PATTERN/</CODE></A>.  If ``''' is used as the delimiter, no interpolation
  875. is done.  Returns a Perl value which may be used instead of the
  876. corresponding <CODE>/STRING/imosx</CODE> expression.
  877. <P>For example,</P>
  878. <PRE>
  879.     $rex = qr/my.STRING/is;
  880.     s/$rex/foo/;</PRE>
  881. <P>is equivalent to</P>
  882. <PRE>
  883.     s/my.STRING/foo/is;</PRE>
  884. <P>The result may be used as a subpattern in a match:</P>
  885. <PRE>
  886.     $re = qr/$pattern/;
  887.     $string =~ /foo${re}bar/;   # can be interpolated in other patterns
  888.     $string =~ $re;             # or used standalone
  889.     $string =~ /$re/;           # or this way</PRE>
  890. <P>Since Perl may compile the pattern at the moment of execution of <A HREF="../../lib/Pod/perlfunc.html#item_qr"><CODE>qr()</CODE></A>
  891. operator, using <A HREF="../../lib/Pod/perlfunc.html#item_qr"><CODE>qr()</CODE></A> may have speed advantages in some situations,
  892. notably if the result of <A HREF="../../lib/Pod/perlfunc.html#item_qr"><CODE>qr()</CODE></A> is used standalone:</P>
  893. <PRE>
  894.     sub match {
  895.         my $patterns = shift;
  896.         my @compiled = map qr/$_/i, @$patterns;
  897.         grep {
  898.             my $success = 0;
  899.             foreach my $pat (@compiled) {
  900.                 $success = 1, last if /$pat/;
  901.             }
  902.             $success;
  903.         } @_;
  904.     }</PRE>
  905. <P>Precompilation of the pattern into an internal representation at
  906. the moment of <A HREF="../../lib/Pod/perlfunc.html#item_qr"><CODE>qr()</CODE></A> avoids a need to recompile the pattern every
  907. time a match <CODE>/$pat/</CODE> is attempted.  (Perl has many other internal
  908. optimizations, but none would be triggered in the above example if
  909. we did not use <A HREF="../../lib/Pod/perlfunc.html#item_qr"><CODE>qr()</CODE></A> operator.)</P>
  910. <P>Options are:</P>
  911. <PRE>
  912.     i   Do case-insensitive pattern matching.
  913.     m   Treat string as multiple lines.
  914.     o   Compile pattern only once.
  915.     s   Treat string as single line.
  916.     x   Use extended regular expressions.</PRE>
  917. <P>See <A HREF="../../lib/Pod/perlre.html">the perlre manpage</A> for additional information on valid syntax for STRING, and
  918. for a detailed look at the semantics of regular expressions.</P>
  919. <P></P>
  920. <DT><STRONG><A NAME="item_qx/">qx/STRING/</A></STRONG><BR>
  921. <DD>
  922. <DT><STRONG><A NAME="item_%60STRING%60">`STRING`</A></STRONG><BR>
  923. <DD>
  924. A string which is (possibly) interpolated and then executed as a system
  925. command with <CODE>/bin/sh</CODE> or its equivalent.  Shell wildcards, pipes,
  926. and redirections will be honored.  The collected standard output of the
  927. command is returned; standard error is unaffected.  In scalar context,
  928. it comes back as a single (potentially multi-line) string.  In list
  929. context, returns a list of lines (however you've defined lines with $/
  930. or $INPUT_RECORD_SEPARATOR).
  931. <P>Because backticks do not affect standard error, use shell file descriptor
  932. syntax (assuming the shell supports this) if you care to address this.
  933. To capture a command's STDERR and STDOUT together:</P>
  934. <PRE>
  935.     $output = `cmd 2>&1`;</PRE>
  936. <P>To capture a command's STDOUT but discard its STDERR:</P>
  937. <PRE>
  938.     $output = `cmd 2>/dev/null`;</PRE>
  939. <P>To capture a command's STDERR but discard its STDOUT (ordering is
  940. important here):</P>
  941. <PRE>
  942.     $output = `cmd 2>&1 1>/dev/null`;</PRE>
  943. <P>To exchange a command's STDOUT and STDERR in order to capture the STDERR
  944. but leave its STDOUT to come out the old STDERR:</P>
  945. <PRE>
  946.     $output = `cmd 3>&1 1>&2 2>&3 3>&-`;</PRE>
  947. <P>To read both a command's STDOUT and its STDERR separately, it's easiest
  948. and safest to redirect them separately to files, and then read from those
  949. files when the program is done:</P>
  950. <PRE>
  951.     system("program args 1>/tmp/program.stdout 2>/tmp/program.stderr");</PRE>
  952. <P>Using single-quote as a delimiter protects the command from Perl's
  953. double-quote interpolation, passing it on to the shell instead:</P>
  954. <PRE>
  955.     $perl_info  = qx(ps $$);            # that's Perl's $$
  956.     $shell_info = qx'ps $$';            # that's the new shell's $$</PRE>
  957. <P>How that string gets evaluated is entirely subject to the command
  958. interpreter on your system.  On most platforms, you will have to protect
  959. shell metacharacters if you want them treated literally.  This is in
  960. practice difficult to do, as it's unclear how to escape which characters.
  961. See <A HREF="../../lib/Pod/perlsec.html">the perlsec manpage</A> for a clean and safe example of a manual <A HREF="../../lib/Pod/perlfunc.html#item_fork"><CODE>fork()</CODE></A> and <A HREF="../../lib/Pod/perlfunc.html#item_exec"><CODE>exec()</CODE></A>
  962. to emulate backticks safely.</P>
  963. <P>On some platforms (notably DOS-like ones), the shell may not be
  964. capable of dealing with multiline commands, so putting newlines in
  965. the string may not get you what you want.  You may be able to evaluate
  966. multiple commands in a single line by separating them with the command
  967. separator character, if your shell supports that (e.g. <CODE>;</CODE> on many Unix
  968. shells; <CODE>&</CODE> on the Windows NT <CODE>cmd</CODE> shell).</P>
  969. <P>Beginning with v5.6.0, Perl will attempt to flush all files opened for
  970. output before starting the child process, but this may not be supported
  971. on some platforms (see <A HREF="../../lib/Pod/perlport.html">the perlport manpage</A>).  To be safe, you may need to set
  972. <CODE>$|</CODE> ($AUTOFLUSH in English) or call the <A HREF="../../lib/Pod/perlvar.html#item_autoflush"><CODE>autoflush()</CODE></A> method of
  973. <CODE>IO::Handle</CODE> on any open handles.</P>
  974. <P>Beware that some command shells may place restrictions on the length
  975. of the command line.  You must ensure your strings don't exceed this
  976. limit after any necessary interpolations.  See the platform-specific
  977. release notes for more details about your particular environment.</P>
  978. <P>Using this operator can lead to programs that are difficult to port,
  979. because the shell commands called vary between systems, and may in
  980. fact not be present at all.  As one example, the <CODE>type</CODE> command under
  981. the POSIX shell is very different from the <CODE>type</CODE> command under DOS.
  982. That doesn't mean you should go out of your way to avoid backticks
  983. when they're the right way to get something done.  Perl was made to be
  984. a glue language, and one of the things it glues together is commands.
  985. Just understand what you're getting yourself into.</P>
  986. <P>See <A HREF="#i/o operators">I/O Operators</A> for more discussion.</P>
  987. <P></P>
  988. <DT><STRONG><A NAME="item_qw/">qw/STRING/</A></STRONG><BR>
  989. <DD>
  990. Evaluates to a list of the words extracted out of STRING, using embedded
  991. whitespace as the word delimiters.  It can be understood as being roughly
  992. equivalent to:
  993. <PRE>
  994.     split(' ', q/STRING/);</PRE>
  995. <P>the difference being that it generates a real list at compile time.  So
  996. this expression:</P>
  997. <PRE>
  998.     qw(foo bar baz)</PRE>
  999. <P>is semantically equivalent to the list:</P>
  1000. <PRE>
  1001.     'foo', 'bar', 'baz'</PRE>
  1002. <P>Some frequently seen examples:</P>
  1003. <PRE>
  1004.     use POSIX qw( setlocale localeconv )
  1005.     @EXPORT = qw( foo bar baz );</PRE>
  1006. <P>A common mistake is to try to separate the words with comma or to
  1007. put comments into a multi-line <A HREF="../../lib/Pod/perlfunc.html#item_qw"><CODE>qw</CODE></A>-string.  For this reason, the
  1008. <CODE>use warnings</CODE> pragma and the <STRONG>-w</STRONG> switch (that is, the <CODE>$^W</CODE> variable) 
  1009. produces warnings if the STRING contains the ``,'' or the ``#'' character.</P>
  1010. <P></P>
  1011. <DT><STRONG><A NAME="item_s/">s/PATTERN/REPLACEMENT/egimosx</A></STRONG><BR>
  1012. <DD>
  1013. Searches a string for a pattern, and if found, replaces that pattern
  1014. with the replacement text and returns the number of substitutions
  1015. made.  Otherwise it returns false (specifically, the empty string).
  1016. <P>If no string is specified via the <CODE>=~</CODE> or <CODE>!~</CODE> operator, the <CODE>$_</CODE>
  1017. variable is searched and modified.  (The string specified with <CODE>=~</CODE> must
  1018. be scalar variable, an array element, a hash element, or an assignment
  1019. to one of those, i.e., an lvalue.)</P>
  1020. <P>If the delimiter chosen is a single quote, no interpolation is
  1021. done on either the PATTERN or the REPLACEMENT.  Otherwise, if the
  1022. PATTERN contains a $ that looks like a variable rather than an
  1023. end-of-string test, the variable will be interpolated into the pattern
  1024. at run-time.  If you want the pattern compiled only once the first time
  1025. the variable is interpolated, use the <CODE>/o</CODE> option.  If the pattern
  1026. evaluates to the empty string, the last successfully executed regular
  1027. expression is used instead.  See <A HREF="../../lib/Pod/perlre.html">the perlre manpage</A> for further explanation on these.
  1028. See <A HREF="../../lib/Pod/perllocale.html">the perllocale manpage</A> for discussion of additional considerations that apply
  1029. when <CODE>use locale</CODE> is in effect.</P>
  1030. <P>Options are:</P>
  1031. <PRE>
  1032.     e   Evaluate the right side as an expression.
  1033.     g   Replace globally, i.e., all occurrences.
  1034.     i   Do case-insensitive pattern matching.
  1035.     m   Treat string as multiple lines.
  1036.     o   Compile pattern only once.
  1037.     s   Treat string as single line.
  1038.     x   Use extended regular expressions.</PRE>
  1039. <P>Any non-alphanumeric, non-whitespace delimiter may replace the
  1040. slashes.  If single quotes are used, no interpretation is done on the
  1041. replacement string (the <CODE>/e</CODE> modifier overrides this, however).  Unlike
  1042. Perl 4, Perl 5 treats backticks as normal delimiters; the replacement
  1043. text is not evaluated as a command.  If the
  1044. PATTERN is delimited by bracketing quotes, the REPLACEMENT has its own
  1045. pair of quotes, which may or may not be bracketing quotes, e.g.,
  1046. <A HREF="../../lib/Pod/perlfunc.html#item_s"><CODE>s(foo)(bar)</CODE></A> or <CODE>s<foo>/bar/</CODE>.  A <CODE>/e</CODE> will cause the
  1047. replacement portion to be treated as a full-fledged Perl expression
  1048. and evaluated right then and there.  It is, however, syntax checked at
  1049. compile-time. A second <CODE>e</CODE> modifier will cause the replacement portion
  1050. to be <A HREF="../../lib/Pod/perlfunc.html#item_eval"><CODE>eval</CODE></A>ed before being run as a Perl expression.</P>
  1051. <P>Examples:</P>
  1052. <PRE>
  1053.     s/\bgreen\b/mauve/g;                # don't change wintergreen</PRE>
  1054. <PRE>
  1055.     $path =~ s|/usr/bin|/usr/local/bin|;</PRE>
  1056. <PRE>
  1057.     s/Login: $foo/Login: $bar/; # run-time pattern</PRE>
  1058. <PRE>
  1059.     ($foo = $bar) =~ s/this/that/;      # copy first, then change</PRE>
  1060. <PRE>
  1061.     $count = ($paragraph =~ s/Mister\b/Mr./g);  # get change-count</PRE>
  1062. <PRE>
  1063.     $_ = 'abc123xyz';
  1064.     s/\d+/$&*2/e;               # yields 'abc246xyz'
  1065.     s/\d+/sprintf("%5d",$&)/e;  # yields 'abc  246xyz'
  1066.     s/\w/$& x 2/eg;             # yields 'aabbcc  224466xxyyzz'</PRE>
  1067. <PRE>
  1068.     s/%(.)/$percent{$1}/g;      # change percent escapes; no /e
  1069.     s/%(.)/$percent{$1} || $&/ge;       # expr now, so /e
  1070.     s/^=(\w+)/&pod($1)/ge;      # use function call</PRE>
  1071. <PRE>
  1072.     # expand variables in $_, but dynamics only, using
  1073.     # symbolic dereferencing
  1074.     s/\$(\w+)/${$1}/g;</PRE>
  1075. <PRE>
  1076.     # Add one to the value of any numbers in the string
  1077.     s/(\d+)/1 + $1/eg;</PRE>
  1078. <PRE>
  1079.     # This will expand any embedded scalar variable
  1080.     # (including lexicals) in $_ : First $1 is interpolated
  1081.     # to the variable name, and then evaluated
  1082.     s/(\$\w+)/$1/eeg;</PRE>
  1083. <PRE>
  1084.     # Delete (most) C comments.
  1085.     $program =~ s {
  1086.         /\*     # Match the opening delimiter.
  1087.         .*?     # Match a minimal number of characters.
  1088.         \*/     # Match the closing delimiter.
  1089.     } []gsx;</PRE>
  1090. <PRE>
  1091.     s/^\s*(.*?)\s*$/$1/;        # trim white space in $_, expensively</PRE>
  1092. <PRE>
  1093.     for ($variable) {           # trim white space in $variable, cheap
  1094.         s/^\s+//;
  1095.         s/\s+$//;
  1096.     }</PRE>
  1097. <PRE>
  1098.     s/([^ ]*) *([^ ]*)/$2 $1/;  # reverse 1st two fields</PRE>
  1099. <P>Note the use of $ instead of \ in the last example.  Unlike
  1100. <STRONG>sed</STRONG>, we use the \<<EM>digit</EM>> form in only the left hand side.
  1101. Anywhere else it's $<<EM>digit</EM>>.</P>
  1102. <P>Occasionally, you can't use just a <CODE>/g</CODE> to get all the changes
  1103. to occur that you might want.  Here are two common cases:</P>
  1104. <PRE>
  1105.     # put commas in the right places in an integer
  1106.     1 while s/(\d)(\d\d\d)(?!\d)/$1,$2/g;</PRE>
  1107. <PRE>
  1108.     # expand tabs to 8-column spacing
  1109.     1 while s/\t+/' ' x (length($&)*8 - length($`)%8)/e;</PRE>
  1110. <P></P>
  1111. <DT><STRONG><A NAME="item_tr/">tr/SEARCHLIST/REPLACEMENTLIST/cdsUC</A></STRONG><BR>
  1112. <DD>
  1113. <DT><STRONG><A NAME="item_y/">y/SEARCHLIST/REPLACEMENTLIST/cdsUC</A></STRONG><BR>
  1114. <DD>
  1115. Transliterates all occurrences of the characters found in the search list
  1116. with the corresponding character in the replacement list.  It returns
  1117. the number of characters replaced or deleted.  If no string is
  1118. specified via the =~ or !~ operator, the $_ string is transliterated.  (The
  1119. string specified with =~ must be a scalar variable, an array element, a
  1120. hash element, or an assignment to one of those, i.e., an lvalue.)
  1121. <P>A character range may be specified with a hyphen, so <A HREF="#item_tr/"><CODE>tr/A-J/0-9/</CODE></A> 
  1122. does the same replacement as <A HREF="#item_tr/"><CODE>tr/ACEGIBDFHJ/0246813579/</CODE></A>.
  1123. For <STRONG>sed</STRONG> devotees, <A HREF="../../lib/Pod/perlfunc.html#item_y"><CODE>y</CODE></A> is provided as a synonym for <A HREF="../../lib/Pod/perlfunc.html#item_tr"><CODE>tr</CODE></A>.  If the
  1124. SEARCHLIST is delimited by bracketing quotes, the REPLACEMENTLIST has
  1125. its own pair of quotes, which may or may not be bracketing quotes,
  1126. e.g., <CODE>tr[A-Z][a-z]</CODE> or <A HREF="../../lib/Pod/perlfunc.html#item_tr"><CODE>tr(+\-*/)/ABCD/</CODE></A>.</P>
  1127. <P>Note also that the whole range idea is rather unportable between
  1128. character sets--and even within character sets they may cause results
  1129. you probably didn't expect.  A sound principle is to use only ranges
  1130. that begin from and end at either alphabets of equal case (a-e, A-E),
  1131. or digits (0-4).  Anything else is unsafe.  If in doubt, spell out the
  1132. character sets in full.</P>
  1133. <P>Options:</P>
  1134. <PRE>
  1135.     c   Complement the SEARCHLIST.
  1136.     d   Delete found but unreplaced characters.
  1137.     s   Squash duplicate replaced characters.
  1138.     U   Translate to/from UTF-8.
  1139.     C   Translate to/from 8-bit char (octet).</PRE>
  1140. <P>If the <CODE>/c</CODE> modifier is specified, the SEARCHLIST character set
  1141. is complemented.  If the <CODE>/d</CODE> modifier is specified, any characters
  1142. specified by SEARCHLIST not found in REPLACEMENTLIST are deleted.
  1143. (Note that this is slightly more flexible than the behavior of some
  1144. <STRONG>tr</STRONG> programs, which delete anything they find in the SEARCHLIST,
  1145. period.) If the <CODE>/s</CODE> modifier is specified, sequences of characters
  1146. that were transliterated to the same character are squashed down
  1147. to a single instance of the character.</P>
  1148. <P>If the <CODE>/d</CODE> modifier is used, the REPLACEMENTLIST is always interpreted
  1149. exactly as specified.  Otherwise, if the REPLACEMENTLIST is shorter
  1150. than the SEARCHLIST, the final character is replicated till it is long
  1151. enough.  If the REPLACEMENTLIST is empty, the SEARCHLIST is replicated.
  1152. This latter is useful for counting characters in a class or for
  1153. squashing character sequences in a class.</P>
  1154. <P>The first <CODE>/U</CODE> or <CODE>/C</CODE> modifier applies to the left side of the translation.
  1155. The second one applies to the right side.  If present, these modifiers override
  1156. the current utf8 state.</P>
  1157. <P>Examples:</P>
  1158. <PRE>
  1159.     $ARGV[1] =~ tr/A-Z/a-z/;    # canonicalize to lower case</PRE>
  1160. <PRE>
  1161.     $cnt = tr/*/*/;             # count the stars in $_</PRE>
  1162. <PRE>
  1163.     $cnt = $sky =~ tr/*/*/;     # count the stars in $sky</PRE>
  1164. <PRE>
  1165.     $cnt = tr/0-9//;            # count the digits in $_</PRE>
  1166. <PRE>
  1167.     tr/a-zA-Z//s;               # bookkeeper -> bokeper</PRE>
  1168. <PRE>
  1169.     ($HOST = $host) =~ tr/a-z/A-Z/;</PRE>
  1170. <PRE>
  1171.     tr/a-zA-Z/ /cs;             # change non-alphas to single space</PRE>
  1172. <PRE>
  1173.     tr [\200-\377]
  1174.        [\000-\177];             # delete 8th bit</PRE>
  1175. <PRE>
  1176.     tr/\0-\xFF//CU;             # change Latin-1 to Unicode
  1177.     tr/\0-\x{FF}//UC;           # change Unicode to Latin-1</PRE>
  1178. <P>If multiple transliterations are given for a character, only the
  1179. first one is used:</P>
  1180. <PRE>
  1181.     tr/AAA/XYZ/</PRE>
  1182. <P>will transliterate any A to X.</P>
  1183. <P>Because the transliteration table is built at compile time, neither
  1184. the SEARCHLIST nor the REPLACEMENTLIST are subjected to double quote
  1185. interpolation.  That means that if you want to use variables, you
  1186. must use an eval():</P>
  1187. <PRE>
  1188.     eval "tr/$oldlist/$newlist/";
  1189.     die $@ if $@;</PRE>
  1190. <PRE>
  1191.     eval "tr/$oldlist/$newlist/, 1" or die $@;</PRE>
  1192. <P></P></DL>
  1193. <P>
  1194. <H2><A NAME="gory details of parsing quoted constructs">Gory details of parsing quoted constructs</A></H2>
  1195. <P>When presented with something that might have several different
  1196. interpretations, Perl uses the <STRONG>DWIM</STRONG> (that's ``Do What I Mean'')
  1197. principle to pick the most probable interpretation.  This strategy
  1198. is so successful that Perl programmers often do not suspect the
  1199. ambivalence of what they write.  But from time to time, Perl's
  1200. notions differ substantially from what the author honestly meant.</P>
  1201. <P>This section hopes to clarify how Perl handles quoted constructs.
  1202. Although the most common reason to learn this is to unravel labyrinthine
  1203. regular expressions, because the initial steps of parsing are the
  1204. same for all quoting operators, they are all discussed together.</P>
  1205. <P>The most important Perl parsing rule is the first one discussed
  1206. below: when processing a quoted construct, Perl first finds the end
  1207. of that construct, then interprets its contents.  If you understand
  1208. this rule, you may skip the rest of this section on the first
  1209. reading.  The other rules are likely to contradict the user's
  1210. expectations much less frequently than this first one.</P>
  1211. <P>Some passes discussed below are performed concurrently, but because
  1212. their results are the same, we consider them individually.  For different
  1213. quoting constructs, Perl performs different numbers of passes, from
  1214. one to five, but these passes are always performed in the same order.</P>
  1215. <DL>
  1216. <DT><STRONG><A NAME="item_Finding_the_end">Finding the end</A></STRONG><BR>
  1217. <DD>
  1218. The first pass is finding the end of the quoted construct, whether
  1219. it be a multicharacter delimiter <CODE>"\nEOF\n"</CODE> in the <CODE><<EOF</CODE>
  1220. construct, a <CODE>/</CODE> that terminates a <A HREF="#item_qq/"><CODE>qq//</CODE></A> construct, a <CODE>]</CODE> which
  1221. terminates <CODE>qq[]</CODE> construct, or a <CODE>></CODE> which terminates a
  1222. fileglob started with <CODE><</CODE>.
  1223. <P>When searching for single-character non-pairing delimiters, such
  1224. as <CODE>/</CODE>, combinations of <CODE>\\</CODE> and <CODE>\/</CODE> are skipped.  However,
  1225. when searching for single-character pairing delimiter like <CODE>[</CODE>,
  1226. combinations of <CODE>\\</CODE>, <CODE>\]</CODE>, and <CODE>\[</CODE> are all skipped, and nested
  1227. <CODE>[</CODE>, <CODE>]</CODE> are skipped as well.  When searching for multicharacter
  1228. delimiters, nothing is skipped.</P>
  1229. <P>For constructs with three-part delimiters (<A HREF="#item_s/"><CODE>s///</CODE></A>, <A HREF="#item_y/"><CODE>y///</CODE></A>, and
  1230. <A HREF="#item_tr/"><CODE>tr///</CODE></A>), the search is repeated once more.</P>
  1231. <P>During this search no attention is paid to the semantics of the construct.
  1232. Thus:</P>
  1233. <PRE>
  1234.     "$hash{"$foo/$bar"}"</PRE>
  1235. <P>or:</P>
  1236. <PRE>
  1237.     m/ 
  1238.       bar       # NOT a comment, this slash / terminated m//!
  1239.      /x</PRE>
  1240. <P>do not form legal quoted expressions.   The quoted part ends on the
  1241. first <CODE>"</CODE> and <CODE>/</CODE>, and the rest happens to be a syntax error.
  1242. Because the slash that terminated <A HREF="#item_m/"><CODE>m//</CODE></A> was followed by a <CODE>SPACE</CODE>,
  1243. the example above is not <A HREF="#item_m/"><CODE>m//x</CODE></A>, but rather <A HREF="#item_m/"><CODE>m//</CODE></A> with no <CODE>/x</CODE>
  1244. modifier.  So the embedded <CODE>#</CODE> is interpreted as a literal <CODE>#</CODE>.</P>
  1245. <P></P>
  1246. <DT><STRONG><A NAME="item_Removal_of_backslashes_before_delimiters">Removal of backslashes before delimiters</A></STRONG><BR>
  1247. <DD>
  1248. During the second pass, text between the starting and ending
  1249. delimiters is copied to a safe location, and the <CODE>\</CODE> is removed
  1250. from combinations consisting of <CODE>\</CODE> and delimiter--or delimiters,
  1251. meaning both starting and ending delimiters will should these differ.
  1252. This removal does not happen for multi-character delimiters.
  1253. Note that the combination <CODE>\\</CODE> is left intact, just as it was.
  1254. <P>Starting from this step no information about the delimiters is
  1255. used in parsing.</P>
  1256. <P></P>
  1257. <DT><STRONG><A NAME="item_Interpolation">Interpolation</A></STRONG><BR>
  1258. <DD>
  1259. The next step is interpolation in the text obtained, which is now
  1260. delimiter-independent.  There are four different cases.
  1261. <DL>
  1262. <DT><STRONG><A NAME="item_%3C%3C%27EOF%27%2C_m%27%27%2C_s%27%27%27%2C_tr%2F%"><CODE><<'EOF'</CODE>, <CODE>m''</CODE>, <CODE>s'''</CODE>, <A HREF="#item_tr/"><CODE>tr///</CODE></A>, <A HREF="#item_y/"><CODE>y///</CODE></A></A></STRONG><BR>
  1263. <DD>
  1264. No interpolation is performed.
  1265. <P></P>
  1266. <DT><STRONG><A NAME="item_%27%27%2C_q%2F%2F"><CODE>''</CODE>, <A HREF="#item_q/"><CODE>q//</CODE></A></A></STRONG><BR>
  1267. <DD>
  1268. The only interpolation is removal of <CODE>\</CODE> from pairs <CODE>\\</CODE>.
  1269. <P></P>
  1270. <DT><STRONG><A NAME="item_%22%22%2C_%60%60%2C_qq%2F%2F%2C_qx%2F%2F%2C_%3Cfil"><CODE>""</CODE>, <CODE>``</CODE>, <A HREF="#item_qq/"><CODE>qq//</CODE></A>, <A HREF="#item_qx/"><CODE>qx//</CODE></A>, <CODE><file*glob></CODE></A></STRONG><BR>
  1271. <DD>
  1272. <CODE>\Q</CODE>, <CODE>\U</CODE>, <CODE>\u</CODE>, <CODE>\L</CODE>, <CODE>\l</CODE> (possibly paired with <CODE>\E</CODE>) are
  1273. converted to corresponding Perl constructs.  Thus, <CODE>"$foo\Qbaz$bar"</CODE>
  1274. is converted to <A HREF="../../lib/Pod/perlfunc.html#item_quotemeta"><CODE>$foo . (quotemeta("baz" . $bar))</CODE></A> internally.
  1275. The other combinations are replaced with appropriate expansions.
  1276. <P>Let it be stressed that <EM>whatever falls between <CODE>\Q</CODE> and <CODE>\E</CODE></EM>
  1277. is interpolated in the usual way.  Something like <CODE>"\Q\\E"</CODE> has
  1278. no <CODE>\E</CODE> inside.  instead, it has <CODE>\Q</CODE>, <CODE>\\</CODE>, and <CODE>E</CODE>, so the
  1279. result is the same as for <CODE>"\\\\E"</CODE>.  As a general rule, backslashes
  1280. between <CODE>\Q</CODE> and <CODE>\E</CODE> may lead to counterintuitive results.  So,
  1281. <CODE>"\Q\t\E"</CODE> is converted to <A HREF="../../lib/Pod/perlfunc.html#item_quotemeta"><CODE>quotemeta("\t")</CODE></A>, which is the same
  1282. as <CODE>"\\\t"</CODE> (since TAB is not alphanumeric).  Note also that:</P>
  1283. <PRE>
  1284.   $str = '\t';
  1285.   return "\Q$str";</PRE>
  1286. <P>may be closer to the conjectural <EM>intention</EM> of the writer of <CODE>"\Q\t\E"</CODE>.</P>
  1287. <P>Interpolated scalars and arrays are converted internally to the <A HREF="../../lib/Pod/perlfunc.html#item_join"><CODE>join</CODE></A> and
  1288. <CODE>.</CODE> catentation operations.  Thus, <CODE>"$foo XXX '@arr'"</CODE> becomes:</P>
  1289. <PRE>
  1290.   $foo . " XXX '" . (join $", @arr) . "'";</PRE>
  1291. <P>All operations above are performed simultaneously, left to right.</P>
  1292. <P>Because the result of <CODE>"\Q STRING \E"</CODE> has all metacharacters
  1293. quoted, there is no way to insert a literal <CODE>$</CODE> or <CODE>@</CODE> inside a
  1294. <CODE>\Q\E</CODE> pair.  If protected by <CODE>\</CODE>, <CODE>$</CODE> will be quoted to became
  1295. <CODE>"\\\$"</CODE>; if not, it is interpreted as the start of an interpolated
  1296. scalar.</P>
  1297. <P>Note also that the interpolation code needs to make a decision on
  1298. where the interpolated scalar ends.  For instance, whether 
  1299. <CODE>"a $b -> {c}"</CODE> really means:</P>
  1300. <PRE>
  1301.   "a " . $b . " -> {c}";</PRE>
  1302. <P>or:</P>
  1303. <PRE>
  1304.   "a " . $b -> {c};</PRE>
  1305. <P>Most of the time, the longest possible text that does not include
  1306. spaces between components and which contains matching braces or
  1307. brackets.  because the outcome may be determined by voting based
  1308. on heuristic estimators, the result is not strictly predictable.
  1309. Fortunately, it's usually correct for ambiguous cases.</P>
  1310. <P></P>
  1311. <DT><STRONG><A NAME="item_%3FRE%3F%2C_%2FRE%2F%2C_m%2FRE%2F%2C_s%2FRE%2Ffoo%"><CODE>?RE?</CODE>, <CODE>/RE/</CODE>, <A HREF="#item_m/"><CODE>m/RE/</CODE></A>, <A HREF="#item_s/"><CODE>s/RE/foo/</CODE></A>,</A></STRONG><BR>
  1312. <DD>
  1313. Processing of <CODE>\Q</CODE>, <CODE>\U</CODE>, <CODE>\u</CODE>, <CODE>\L</CODE>, <CODE>\l</CODE>, and interpolation
  1314. happens (almost) as with <A HREF="#item_qq/"><CODE>qq//</CODE></A> constructs, but the substitution
  1315. of <CODE>\</CODE> followed by RE-special chars (including <CODE>\</CODE>) is not
  1316. performed.  Moreover, inside <CODE>(?{BLOCK})</CODE>, <CODE>(?# comment )</CODE>, and
  1317. a <CODE>#</CODE>-comment in a <CODE>//x</CODE>-regular expression, no processing is
  1318. performed whatsoever.  This is the first step at which the presence
  1319. of the <CODE>//x</CODE> modifier is relevant.
  1320. <P>Interpolation has several quirks: <CODE>$|</CODE>, <CODE>$(</CODE>, and <CODE>$)</CODE> are not
  1321. interpolated, and constructs <CODE>$var[SOMETHING]</CODE> are voted (by several
  1322. different estimators) to be either an array element or <CODE>$var</CODE>
  1323. followed by an RE alternative.  This is where the notation
  1324. <CODE>${arr[$bar]}</CODE> comes handy: <CODE>/${arr[0-9]}/</CODE> is interpreted as
  1325. array element <CODE>-9</CODE>, not as a regular expression from the variable
  1326. <CODE>$arr</CODE> followed by a digit, which would be the interpretation of
  1327. <CODE>/$arr[0-9]/</CODE>.  Since voting among different estimators may occur,
  1328. the result is not predictable.</P>
  1329. <P>It is at this step that <CODE>\1</CODE> is begrudgingly converted to <CODE>$1</CODE> in
  1330. the replacement text of <A HREF="#item_s/"><CODE>s///</CODE></A> to correct the incorrigible
  1331. <EM>sed</EM> hackers who haven't picked up the saner idiom yet.  A warning
  1332. is emitted if the <CODE>use warnings</CODE> pragma or the <STRONG>-w</STRONG> command-line flag
  1333. (that is, the <CODE>$^W</CODE> variable) was set.</P>
  1334. <P>The lack of processing of <CODE>\\</CODE> creates specific restrictions on
  1335. the post-processed text.  If the delimiter is <CODE>/</CODE>, one cannot get
  1336. the combination <CODE>\/</CODE> into the result of this step.  <CODE>/</CODE> will
  1337. finish the regular expression, <CODE>\/</CODE> will be stripped to <CODE>/</CODE> on
  1338. the previous step, and <CODE>\\/</CODE> will be left as is.  Because <CODE>/</CODE> is
  1339. equivalent to <CODE>\/</CODE> inside a regular expression, this does not
  1340. matter unless the delimiter happens to be character special to the
  1341. RE engine, such as in <CODE>s*foo*bar*</CODE>, <CODE>m[foo]</CODE>, or <CODE>?foo?</CODE>; or an
  1342. alphanumeric char, as in:</P>
  1343. <PRE>
  1344.   m m ^ a \s* b mmx;</PRE>
  1345. <P>In the RE above, which is intentionally obfuscated for illustration, the
  1346. delimiter is <A HREF="../../lib/Pod/perlfunc.html#item_m"><CODE>m</CODE></A>, the modifier is <CODE>mx</CODE>, and after backslash-removal the
  1347. RE is the same as for <A HREF="#item_m/"><CODE>m/ ^ a s* b /mx</CODE></A>).  There's more than one 
  1348. reason you're encouraged to restrict your delimiters to non-alphanumeric,
  1349. non-whitespace choices.</P>
  1350. <P></P></DL>
  1351. <P>This step is the last one for all constructs except regular expressions,
  1352. which are processed further.</P>
  1353. <DT><STRONG><A NAME="item_Interpolation_of_regular_expressions">Interpolation of regular expressions</A></STRONG><BR>
  1354. <DD>
  1355. Previous steps were performed during the compilation of Perl code,
  1356. but this one happens at run time--although it may be optimized to
  1357. be calculated at compile time if appropriate.  After preprocessing
  1358. described above, and possibly after evaluation if catenation,
  1359. joining, casing translation, or metaquoting are involved, the
  1360. resulting <EM>string</EM> is passed to the RE engine for compilation.
  1361. <P>Whatever happens in the RE engine might be better discussed in <A HREF="../../lib/Pod/perlre.html">the perlre manpage</A>,
  1362. but for the sake of continuity, we shall do so here.</P>
  1363. <P>This is another step where the presence of the <CODE>//x</CODE> modifier is
  1364. relevant.  The RE engine scans the string from left to right and
  1365. converts it to a finite automaton.</P>
  1366. <P>Backslashed characters are either replaced with corresponding
  1367. literal strings (as with <CODE>\{</CODE>), or else they generate special nodes
  1368. in the finite automaton (as with <CODE>\b</CODE>).  Characters special to the
  1369. RE engine (such as <CODE>|</CODE>) generate corresponding nodes or groups of
  1370. nodes.  <CODE>(?#...)</CODE> comments are ignored.  All the rest is either
  1371. converted to literal strings to match, or else is ignored (as is
  1372. whitespace and <CODE>#</CODE>-style comments if <CODE>//x</CODE> is present).</P>
  1373. <P>Parsing of the bracketed character class construct, <CODE>[...]</CODE>, is
  1374. rather different than the rule used for the rest of the pattern.
  1375. The terminator of this construct is found using the same rules as
  1376. for finding the terminator of a <CODE>{}</CODE>-delimited construct, the only
  1377. exception being that <CODE>]</CODE> immediately following <CODE>[</CODE> is treated as
  1378. though preceded by a backslash.  Similarly, the terminator of
  1379. <CODE>(?{...})</CODE> is found using the same rules as for finding the
  1380. terminator of a <CODE>{}</CODE>-delimited construct.</P>
  1381. <P>It is possible to inspect both the string given to RE engine and the
  1382. resulting finite automaton.  See the arguments <CODE>debug</CODE>/<CODE>debugcolor</CODE>
  1383. in the <CODE>use re</CODE> pragma, as well as Perl's <STRONG>-Dr</STRONG> command-line
  1384. switch documented in <A HREF="../../lib/Pod/perlrun.html#command switches">Command Switches in the perlrun manpage</A>.</P>
  1385. <P></P>
  1386. <DT><STRONG><A NAME="item_Optimization_of_regular_expressions">Optimization of regular expressions</A></STRONG><BR>
  1387. <DD>
  1388. This step is listed for completeness only.  Since it does not change
  1389. semantics, details of this step are not documented and are subject
  1390. to change without notice.  This step is performed over the finite
  1391. automaton that was generated during the previous pass.
  1392. <P>It is at this stage that <A HREF="../../lib/Pod/perlfunc.html#item_split"><CODE>split()</CODE></A> silently optimizes <CODE>/^/</CODE> to
  1393. mean <CODE>/^/m</CODE>.</P>
  1394. <P></P></DL>
  1395. <P>
  1396. <H2><A NAME="i/o operators">I/O Operators</A></H2>
  1397. <P>There are several I/O operators you should know about.</P>
  1398. <P>A string enclosed by backticks (grave accents) first undergoes
  1399. double-quote interpolation.  It is then interpreted as an external
  1400. command, and the output of that command is the value of the
  1401. pseudo-literal, j
  1402. string consisting of all output is returned.  In list context, a
  1403. list of values is returned, one per line of output.  (You can set
  1404. <CODE>$/</CODE> to use a different line terminator.)  The command is executed
  1405. each time the pseudo-literal is evaluated.  The status value of the
  1406. command is returned in <CODE>$?</CODE> (see <A HREF="../../lib/Pod/perlvar.html">the perlvar manpage</A> for the interpretation
  1407. of <CODE>$?</CODE>).  Unlike in <STRONG>csh</STRONG>, no translation is done on the return
  1408. data--newlines remain newlines.  Unlike in any of the shells, single
  1409. quotes do not hide variable names in the command from interpretation.
  1410. To pass a literal dollar-sign through to the shell you need to hide
  1411. it with a backslash.  The generalized form of backticks is <A HREF="#item_qx/"><CODE>qx//</CODE></A>.
  1412. (Because backticks always undergo shell expansion as well, see
  1413. <A HREF="../../lib/Pod/perlsec.html">the perlsec manpage</A> for security concerns.)</P>
  1414. <P>In scalar context, evaluating a filehandle in angle brackets yields
  1415. the next line from that file (the newline, if any, included), or
  1416. <A HREF="../../lib/Pod/perlfunc.html#item_undef"><CODE>undef</CODE></A> at end-of-file or on error.  When <CODE>$/</CODE> is set to <A HREF="../../lib/Pod/perlfunc.html#item_undef"><CODE>undef</CODE></A>
  1417. (sometimes known as file-slurp mode) and the file is empty, it
  1418. returns <CODE>''</CODE> the first time, followed by <A HREF="../../lib/Pod/perlfunc.html#item_undef"><CODE>undef</CODE></A> subsequently.</P>
  1419. <P>Ordinarily you must assign the returned value to a variable, but
  1420. there is one situation where an automatic assignment happens.  If
  1421. and only if the input symbol is the only thing inside the conditional
  1422. of a <CODE>while</CODE> statement (even if disguised as a <CODE>for(;;)</CODE> loop),
  1423. the value is automatically assigned to the global variable $_,
  1424. destroying whatever was there previously.  (This may seem like an
  1425. odd thing to you, but you'll use the construct in almost every Perl
  1426. script you write.)  The $_ variables is not implicitly localized.
  1427. You'll have to put a <CODE>local $_;</CODE> before the loop if you want that
  1428. to happen.</P>
  1429. <P>The following lines are equivalent:</P>
  1430. <PRE>
  1431.     while (defined($_ = <STDIN>)) { print; }
  1432.     while ($_ = <STDIN>) { print; }
  1433.     while (<STDIN>) { print; }
  1434.     for (;<STDIN>;) { print; }
  1435.     print while defined($_ = <STDIN>);
  1436.     print while ($_ = <STDIN>);
  1437.     print while <STDIN>;</PRE>
  1438. <P>This also behaves similarly, but avoids $_ :</P>
  1439. <PRE>
  1440.     while (my $line = <STDIN>) { print $line }</PRE>
  1441. <P>In these loop constructs, the assigned value (whether assignment
  1442. is automatic or explicit) is then tested to see whether it is
  1443. defined.  The defined test avoids problems where line has a string
  1444. value that would be treated as false by Perl, for example a ``'' or
  1445. a ``0'' with no trailing newline.  If you really mean for such values
  1446. to terminate the loop, they should be tested for explicitly:</P>
  1447. <PRE>
  1448.     while (($_ = <STDIN>) ne '0') { ... }
  1449.     while (<STDIN>) { last unless $_; ... }</PRE>
  1450. <P>In other boolean contexts, <CODE><filehandle></CODE> without an
  1451. explicit <A HREF="../../lib/Pod/perlfunc.html#item_defined"><CODE>defined</CODE></A> test or comparison elicit a warning if the 
  1452. <CODE>use warnings</CODE> pragma or the <STRONG>-w</STRONG>
  1453. command-line switch (the <CODE>$^W</CODE> variable) is in effect.</P>
  1454. <P>The filehandles STDIN, STDOUT, and STDERR are predefined.  (The
  1455. filehandles <CODE>stdin</CODE>, <CODE>stdout</CODE>, and <CODE>stderr</CODE> will also work except
  1456. in packages, where they would be interpreted as local identifiers
  1457. rather than global.)  Additional filehandles may be created with
  1458. the <A HREF="../../lib/Pod/perlfunc.html#item_open"><CODE>open()</CODE></A> function, amongst others.  See <A HREF="../../lib/Pod/perlopentut.html">the perlopentut manpage</A> and
  1459. <A HREF="../../lib/Pod/perlfunc.html#open">open in the perlfunc manpage</A> for details on this.</P>
  1460. <P>If a <FILEHANDLE> is used in a context that is looking for
  1461. a list, a list comprising all input lines is returned, one line per
  1462. list element.  It's easy to grow to a rather large data space this
  1463. way, so use with care.</P>
  1464. <P><FILEHANDLE> may also be spelled <A HREF="../../lib/Pod/perlfunc.html#item_readline"><CODE>readline(*FILEHANDLE)</CODE></A>.
  1465. See <A HREF="../../lib/Pod/perlfunc.html#readline">readline in the perlfunc manpage</A>.</P>
  1466. <P>The null filehandle <> is special: it can be used to emulate the
  1467. behavior of <STRONG>sed</STRONG> and <STRONG>awk</STRONG>.  Input from <> comes either from
  1468. standard input, or from each file listed on the command line.  Here's
  1469. how it works: the first time <> is evaluated, the @ARGV array is
  1470. checked, and if it is empty, <CODE>$ARGV[0]</CODE> is set to ``-'', which when opened
  1471. gives you standard input.  The @ARGV array is then processed as a list
  1472. of filenames.  The loop</P>
  1473. <PRE>
  1474.     while (<>) {
  1475.         ...                     # code for each line
  1476.     }</PRE>
  1477. <P>is equivalent to the following Perl-like pseudo code:</P>
  1478. <PRE>
  1479.     unshift(@ARGV, '-') unless @ARGV;
  1480.     while ($ARGV = shift) {
  1481.         open(ARGV, $ARGV);
  1482.         while (<ARGV>) {
  1483.             ...         # code for each line
  1484.         }
  1485.     }</PRE>
  1486. <P>except that it isn't so cumbersome to say, and will actually work.
  1487. It really does shift the @ARGV array and put the current filename
  1488. into the $ARGV variable.  It also uses filehandle <EM>ARGV</EM>
  1489. internally--<> is just a synonym for <ARGV>, which
  1490. is magical.  (The pseudo code above doesn't work because it treats
  1491. <ARGV> as non-magical.)</P>
  1492. <P>You can modify @ARGV before the first <> as long as the array ends up
  1493. containing the list of filenames you really want.  Line numbers (<CODE>$.</CODE>)
  1494. continue as though the input were one big happy file.  See the example
  1495. in <A HREF="../../lib/Pod/perlfunc.html#eof">eof in the perlfunc manpage</A> for how to reset line numbers on each file.</P>
  1496. <P>If you want to set @ARGV to your own list of files, go right ahead.  
  1497. This sets @ARGV to all plain text files if no @ARGV was given:</P>
  1498. <PRE>
  1499.     @ARGV = grep { -f && -T } glob('*') unless @ARGV;</PRE>
  1500. <P>You can even set them to pipe commands.  For example, this automatically
  1501. filters compressed arguments through <STRONG>gzip</STRONG>:</P>
  1502. <PRE>
  1503.     @ARGV = map { /\.(gz|Z)$/ ? "gzip -dc < $_ |" : $_ } @ARGV;</PRE>
  1504. <P>If you want to pass switches into your script, you can use one of the
  1505. Getopts modules or put a loop on the front like this:</P>
  1506. <PRE>
  1507.     while ($_ = $ARGV[0], /^-/) {
  1508.         shift;
  1509.         last if /^--$/;
  1510.         if (/^-D(.*)/) { $debug = $1 }
  1511.         if (/^-v/)     { $verbose++  }
  1512.         # ...           # other switches
  1513.     }</PRE>
  1514. <PRE>
  1515.     while (<>) {
  1516.         # ...           # code for each line
  1517.     }</PRE>
  1518. <P>The <> symbol will return <A HREF="../../lib/Pod/perlfunc.html#item_undef"><CODE>undef</CODE></A> for end-of-file only once.  
  1519. If you call it again after this, it will assume you are processing another 
  1520. @ARGV list, and if you haven't set @ARGV, will read input from STDIN.</P>
  1521. <P>If angle brackets contain is a simple scalar variable (e.g.,
  1522. <$foo>), then that variable contains the name of the
  1523. filehandle to input from, or its typeglob, or a reference to the
  1524. same.  For example:</P>
  1525. <PRE>
  1526.     $fh = \*STDIN;
  1527.     $line = <$fh>;</PRE>
  1528. <P>If what's within the angle brackets is neither a filehandle nor a simple
  1529. scalar variable containing a filehandle name, typeglob, or typeglob
  1530. reference, it is interpreted as a filename pattern to be globbed, and
  1531. either a list of filenames or the next filename in the list is returned,
  1532. depending on context.  This distinction is determined on syntactic
  1533. grounds alone.  That means <CODE><$x></CODE> is always a <A HREF="../../lib/Pod/perlfunc.html#item_readline"><CODE>readline()</CODE></A> from
  1534. an indirect handle, but <CODE><$hash{key}></CODE> is always a glob().
  1535. That's because $x is a simple scalar variable, but <CODE>$hash{key}</CODE> is
  1536. not--it's a hash element.</P>
  1537. <P>One level of double-quote interpretation is done first, but you can't
  1538. say <CODE><$foo></CODE> because that's an indirect filehandle as explained
  1539. in the previous paragraph.  (In older versions of Perl, programmers
  1540. would insert curly brackets to force interpretation as a filename glob:
  1541. <CODE><${foo}></CODE>.  These days, it's considered cleaner to call the
  1542. internal function directly as <A HREF="../../lib/Pod/perlfunc.html#item_glob"><CODE>glob($foo)</CODE></A>, which is probably the right
  1543. way to have done it in the first place.)  For example:</P>
  1544. <PRE>
  1545.     while (<*.c>) {
  1546.         chmod 0644, $_;
  1547.     }</PRE>
  1548. <P>is roughly equivalent to:</P>
  1549. <PRE>
  1550.     open(FOO, "echo *.c | tr -s ' \t\r\f' '\\012\\012\\012\\012'|");
  1551.     while (<FOO>) {
  1552.         chop;
  1553.         chmod 0644, $_;
  1554.     }</PRE>
  1555. <P>except that the globbing is actually done internally using the standard
  1556. <CODE>File::Glob</CODE> extension.  Of course, the shortest way to do the above is:</P>
  1557. <PRE>
  1558.     chmod 0644, <*.c>;</PRE>
  1559. <P>A (file)glob evaluates its (embedded) argument only when it is
  1560. starting a new list.  All values must be read before it will start
  1561. over.  In list context, this isn't important because you automatically
  1562. get them all anyway.  However, in scalar context the operator returns
  1563. the next value each time it's called, or C
  1564. run out.  As with filehandle reads, an automatic <A HREF="../../lib/Pod/perlfunc.html#item_defined"><CODE>defined</CODE></A> is
  1565. generated when the glob occurs in the test part of a <CODE>while</CODE>,
  1566. because legal glob returns (e.g. a file called <EM>0</EM>) would otherwise
  1567. terminate the loop.  Again, <A HREF="../../lib/Pod/perlfunc.html#item_undef"><CODE>undef</CODE></A> is returned only once.  So if
  1568. you're expecting a single value from a glob, it is much better to
  1569. say</P>
  1570. <PRE>
  1571.     ($file) = <blurch*>;</PRE>
  1572. <P>than</P>
  1573. <PRE>
  1574.     $file = <blurch*>;</PRE>
  1575. <P>because the latter will alternate between returning a filename and
  1576. returning false.</P>
  1577. <P>It you're trying to do variable interpolation, it's definitely better
  1578. to use the <A HREF="../../lib/Pod/perlfunc.html#item_glob"><CODE>glob()</CODE></A> function, because the older notation can cause people
  1579. to become confused with the indirect filehandle notation.</P>
  1580. <PRE>
  1581.     @files = glob("$dir/*.[ch]");
  1582.     @files = glob($files[$i]);</PRE>
  1583. <P>
  1584. <H2><A NAME="constant folding">Constant Folding</A></H2>
  1585. <P>Like C, Perl does a certain amount of expression evaluation at
  1586. compile time whenever it determines that all arguments to an
  1587. operator are static and have no side effects.  In particular, string
  1588. concatenation happens at compile time between literals that don't do
  1589. variable substitution.  Backslash interpolation also happens at
  1590. compile time.  You can say</P>
  1591. <PRE>
  1592.     'Now is the time for all' . "\n" .
  1593.         'good men to come to.'</PRE>
  1594. <P>and this all reduces to one string internally.  Likewise, if
  1595. you say</P>
  1596. <PRE>
  1597.     foreach $file (@filenames) {
  1598.         if (-s $file > 5 + 100 * 2**16) {  }
  1599.     }</PRE>
  1600. <P>the compiler will precompute the number which that expression
  1601. represents so that the interpreter won't have to.</P>
  1602. <P>
  1603. <H2><A NAME="bitwise string operators">Bitwise String Operators</A></H2>
  1604. <P>Bitstrings of any size may be manipulated by the bitwise operators
  1605. (<CODE>~ | & ^</CODE>).</P>
  1606. <P>If the operands to a binary bitwise op are strings of different
  1607. sizes, <STRONG>|</STRONG> and <STRONG>^</STRONG> ops act as though the shorter operand had
  1608. additional zero bits on the right, while the <STRONG>&</STRONG> op acts as though
  1609. the longer operand were truncated to the length of the shorter.
  1610. The granularity for such extension or truncation is one or more
  1611. bytes.</P>
  1612. <PRE>
  1613.     # ASCII-based examples 
  1614.     print "j p \n" ^ " a h";            # prints "JAPH\n"
  1615.     print "JA" | "  ph\n";              # prints "japh\n"
  1616.     print "japh\nJunk" & '_____';       # prints "JAPH\n";
  1617.     print 'p N$' ^ " E<H\n";            # prints "Perl\n";</PRE>
  1618. <P>If you are intending to manipulate bitstrings, be certain that
  1619. you're supplying bitstrings: If an operand is a number, that will imply
  1620. a <STRONG>numeric</STRONG> bitwise operation.  You may explicitly show which type of
  1621. operation you intend by using <CODE>""</CODE> or <CODE>0+</CODE>, as in the examples below.</P>
  1622. <PRE>
  1623.     $foo =  150  |  105 ;       # yields 255  (0x96 | 0x69 is 0xFF)
  1624.     $foo = '150' |  105 ;       # yields 255
  1625.     $foo =  150  | '105';       # yields 255
  1626.     $foo = '150' | '105';       # yields string '155' (under ASCII)</PRE>
  1627. <PRE>
  1628.     $baz = 0+$foo & 0+$bar;     # both ops explicitly numeric
  1629.     $biz = "$foo" ^ "$bar";     # both ops explicitly stringy</PRE>
  1630. <P>See <A HREF="../../lib/Pod/perlfunc.html#vec">vec in the perlfunc manpage</A> for information on how to manipulate individual bits
  1631. in a bit vector.</P>
  1632. <P>
  1633. <H2><A NAME="integer arithmetic">Integer Arithmetic</A></H2>
  1634. <P>By default, Perl assumes that it must do most of its arithmetic in
  1635. floating point.  But by saying</P>
  1636. <PRE>
  1637.     use integer;</PRE>
  1638. <P>you may tell the compiler that it's okay to use integer operations
  1639. (if it feels like it) from here to the end of the enclosing BLOCK.
  1640. An inner BLOCK may countermand this by saying</P>
  1641. <PRE>
  1642.     no integer;</PRE>
  1643. <P>which lasts until the end of that BLOCK.  Note that this doesn't
  1644. mean everything is only an integer, merely that Perl may use integer
  1645. operations if it is so inclined.  For example, even under <CODE>use
  1646. integer</CODE>, if you take the <A HREF="../../lib/Pod/perlfunc.html#item_sqrt"><CODE>sqrt(2)</CODE></A>, you'll still get <CODE>1.4142135623731</CODE>
  1647. or so.</P>
  1648. <P>Used on numbers, the bitwise operators (``&'', ``|'', ``^'', ``~'', ``<<'',
  1649. and ``>>'') always produce integral results.  (But see also <A HREF="#bitwise string operators">Bitwise String Operators</A>.)  However, <CODE>use integer</CODE> still has meaning for
  1650. them.  By default, their results are interpreted as unsigned integers, but
  1651. if <CODE>use integer</CODE> is in effect, their results are interpreted
  1652. as signed integers.  For example, <CODE>~0</CODE> usually evaluates to a large
  1653. integral value.  However, <CODE>use integer; ~0</CODE> is <CODE>-1</CODE> on twos-complement
  1654. machines.</P>
  1655. <P>
  1656. <H2><A NAME="floatingpoint arithmetic">Floating-point Arithmetic</A></H2>
  1657. <P>While <CODE>use integer</CODE> provides integer-only arithmetic, there is no
  1658. analogous mechanism to provide automatic rounding or truncation to a
  1659. certain number of decimal places.  For rounding to a certain number
  1660. of digits, <A HREF="../../lib/Pod/perlfunc.html#item_sprintf"><CODE>sprintf()</CODE></A> or <A HREF="../../lib/Pod/perlfunc.html#item_printf"><CODE>printf()</CODE></A> is usually the easiest route.
  1661. See <A HREF="../../lib/Pod/perlfaq4.html">the perlfaq4 manpage</A>.</P>
  1662. <P>Floating-point numbers are only approximations to what a mathematician
  1663. would call real numbers.  There are infinitely more reals than floats,
  1664. so some corners must be cut.  For example:</P>
  1665. <PRE>
  1666.     printf "%.20g\n", 123456789123456789;
  1667.     #        produces 123456789123456784</PRE>
  1668. <P>Testing for exact equality of floating-point equality or inequality is
  1669. not a good idea.  Here's a (relatively expensive) work-around to compare
  1670. whether two floating-point numbers are equal to a particular number of
  1671. decimal places.  See Knuth, volume II, for a more robust treatment of
  1672. this topic.</P>
  1673. <PRE>
  1674.     sub fp_equal {
  1675.         my ($X, $Y, $POINTS) = @_;
  1676.         my ($tX, $tY);
  1677.         $tX = sprintf("%.${POINTS}g", $X);
  1678.         $tY = sprintf("%.${POINTS}g", $Y);
  1679.         return $tX eq $tY;
  1680.     }</PRE>
  1681. <P>The POSIX module (part of the standard perl distribution) implements
  1682. ceil(), floor(), and other mathematical and trigonometric functions.
  1683. The Math::Complex module (part of the standard perl distribution)
  1684. defines mathematical functions that work on both the reals and the
  1685. imaginary numbers.  Math::Complex not as efficient as POSIX, but
  1686. POSIX can't work with complex numbers.</P>
  1687. <P>Rounding in financial applications can have serious implications, and
  1688. the rounding method used should be specified precisely.  In these
  1689. cases, it probably pays not to trust whichever system rounding is
  1690. being used by Perl, but to instead implement the rounding function you
  1691. need yourself.</P>
  1692. <P>
  1693. <H2><A NAME="bigger numbers">Bigger Numbers</A></H2>
  1694. <P>The standard Math::BigInt and Math::BigFloat modules provide
  1695. variable-precision arithmetic and overloaded operators, although
  1696. they're currently pretty slow.  At the cost of some space and
  1697. considerable speed, they avoid the normal pitfalls associated with
  1698. limited-precision representations.</P>
  1699. <PRE>
  1700.     use Math::BigInt;
  1701.     $x = Math::BigInt->new('123456789123456789');
  1702.     print $x * $x;</PRE>
  1703. <PRE>
  1704.     # prints +15241578780673678515622620750190521</PRE>
  1705. <P>The non-standard modules SSLeay::BN and Math::Pari provide
  1706. equivalent functionality (and much more) with a substantial
  1707. performance savings.</P>
  1708. <TABLE BORDER=0 CELLPADDING=0 CELLSPACING=0 WIDTH=100%>
  1709. <TR><TD CLASS=block VALIGN=MIDDLE WIDTH=100% BGCOLOR="#cccccc">
  1710. <STRONG><P CLASS=block> perlop - Perl operators and precedence</P></STRONG>
  1711. </TD></TR>
  1712. </TABLE>
  1713.  
  1714. </BODY>
  1715.  
  1716. </HTML>
  1717.