1PERLOP(1)              Perl Programmers Reference Guide              PERLOP(1)
2
3
4

NAME

6       perlop - Perl operators and precedence
7

DESCRIPTION

9   Operator Precedence and Associativity
10       Operator precedence and associativity work in Perl more or less like
11       they do in mathematics.
12
13       Operator precedence means some operators are evaluated before others.
14       For example, in "2 + 4 * 5", the multiplication has higher precedence
15       so "4 * 5" is evaluated first yielding "2 + 20 == 22" and not "6 * 5 ==
16       30".
17
18       Operator associativity defines what happens if a sequence of the same
19       operators is used one after another: whether the evaluator will
20       evaluate the left operations first or the right.  For example, in "8 -
21       4 - 2", subtraction is left associative so Perl evaluates the
22       expression left to right.  "8 - 4" is evaluated first making the
23       expression "4 - 2 == 2" and not "8 - 2 == 6".
24
25       Perl operators have the following associativity and precedence, listed
26       from highest precedence to lowest.  Operators borrowed from C keep the
27       same precedence relationship with each other, even where C's precedence
28       is slightly screwy.  (This makes learning Perl easier for C folks.)
29       With very few exceptions, these all operate on scalar values only, not
30       array values.
31
32           left        terms and list operators (leftward)
33           left        ->
34           nonassoc    ++ --
35           right       **
36           right       ! ~ \ and unary + and -
37           left        =~ !~
38           left        * / % x
39           left        + - .
40           left        << >>
41           nonassoc    named unary operators
42           nonassoc    < > <= >= lt gt le ge
43           nonassoc    == != <=> eq ne cmp ~~
44           left        &
45           left        | ^
46           left        &&
47           left        || //
48           nonassoc    ..  ...
49           right       ?:
50           right       = += -= *= etc.
51           left        , =>
52           nonassoc    list operators (rightward)
53           right       not
54           left        and
55           left        or xor
56
57       In the following sections, these operators are covered in precedence
58       order.
59
60       Many operators can be overloaded for objects.  See overload.
61
62   Terms and List Operators (Leftward)
63       A TERM has the highest precedence in Perl.  They include variables,
64       quote and quote-like operators, any expression in parentheses, and any
65       function whose arguments are parenthesized.  Actually, there aren't
66       really functions in this sense, just list operators and unary operators
67       behaving as functions because you put parentheses around the arguments.
68       These are all documented in perlfunc.
69
70       If any list operator (print(), etc.) or any unary operator (chdir(),
71       etc.)  is followed by a left parenthesis as the next token, the
72       operator and arguments within parentheses are taken to be of highest
73       precedence, just like a normal function call.
74
75       In the absence of parentheses, the precedence of list operators such as
76       "print", "sort", or "chmod" is either very high or very low depending
77       on whether you are looking at the left side or the right side of the
78       operator.  For example, in
79
80           @ary = (1, 3, sort 4, 2);
81           print @ary;         # prints 1324
82
83       the commas on the right of the sort are evaluated before the sort, but
84       the commas on the left are evaluated after.  In other words, list
85       operators tend to gobble up all arguments that follow, and then act
86       like a simple TERM with regard to the preceding expression.  Be careful
87       with parentheses:
88
89           # These evaluate exit before doing the print:
90           print($foo, exit);  # Obviously not what you want.
91           print $foo, exit;   # Nor is this.
92
93           # These do the print before evaluating exit:
94           (print $foo), exit; # This is what you want.
95           print($foo), exit;  # Or this.
96           print ($foo), exit; # Or even this.
97
98       Also note that
99
100           print ($foo & 255) + 1, "\n";
101
102       probably doesn't do what you expect at first glance.  The parentheses
103       enclose the argument list for "print" which is evaluated (printing the
104       result of "$foo & 255").  Then one is added to the return value of
105       "print" (usually 1).  The result is something like this:
106
107           1 + 1, "\n";    # Obviously not what you meant.
108
109       To do what you meant properly, you must write:
110
111           print(($foo & 255) + 1, "\n");
112
113       See "Named Unary Operators" for more discussion of this.
114
115       Also parsed as terms are the "do {}" and "eval {}" constructs, as well
116       as subroutine and method calls, and the anonymous constructors "[]" and
117       "{}".
118
119       See also "Quote and Quote-like Operators" toward the end of this
120       section, as well as "I/O Operators".
121
122   The Arrow Operator
123       ""->"" is an infix dereference operator, just as it is in C and C++.
124       If the right side is either a "[...]", "{...}", or a "(...)" subscript,
125       then the left side must be either a hard or symbolic reference to an
126       array, a hash, or a subroutine respectively.  (Or technically speaking,
127       a location capable of holding a hard reference, if it's an array or
128       hash reference being used for assignment.)  See perlreftut and perlref.
129
130       Otherwise, the right side is a method name or a simple scalar variable
131       containing either the method name or a subroutine reference, and the
132       left side must be either an object (a blessed reference) or a class
133       name (that is, a package name).  See perlobj.
134
135   Auto-increment and Auto-decrement
136       "++" and "--" work as in C.  That is, if placed before a variable, they
137       increment or decrement the variable by one before returning the value,
138       and if placed after, increment or decrement after returning the value.
139
140           $i = 0;  $j = 0;
141           print $i++;  # prints 0
142           print ++$j;  # prints 1
143
144       Note that just as in C, Perl doesn't define when the variable is
145       incremented or decremented. You just know it will be done sometime
146       before or after the value is returned. This also means that modifying a
147       variable twice in the same statement will lead to undefined behaviour.
148       Avoid statements like:
149
150           $i = $i ++;
151           print ++ $i + $i ++;
152
153       Perl will not guarantee what the result of the above statements is.
154
155       The auto-increment operator has a little extra builtin magic to it.  If
156       you increment a variable that is numeric, or that has ever been used in
157       a numeric context, you get a normal increment.  If, however, the
158       variable has been used in only string contexts since it was set, and
159       has a value that is not the empty string and matches the pattern
160       "/^[a-zA-Z]*[0-9]*\z/", the increment is done as a string, preserving
161       each character within its range, with carry:
162
163           print ++($foo = '99');      # prints '100'
164           print ++($foo = 'a0');      # prints 'a1'
165           print ++($foo = 'Az');      # prints 'Ba'
166           print ++($foo = 'zz');      # prints 'aaa'
167
168       "undef" is always treated as numeric, and in particular is changed to 0
169       before incrementing (so that a post-increment of an undef value will
170       return 0 rather than "undef").
171
172       The auto-decrement operator is not magical.
173
174   Exponentiation
175       Binary "**" is the exponentiation operator.  It binds even more tightly
176       than unary minus, so -2**4 is -(2**4), not (-2)**4. (This is
177       implemented using C's pow(3) function, which actually works on doubles
178       internally.)
179
180   Symbolic Unary Operators
181       Unary "!" performs logical negation, i.e., "not".  See also "not" for a
182       lower precedence version of this.
183
184       Unary "-" performs arithmetic negation if the operand is numeric.  If
185       the operand is an identifier, a string consisting of a minus sign
186       concatenated with the identifier is returned.  Otherwise, if the string
187       starts with a plus or minus, a string starting with the opposite sign
188       is returned.  One effect of these rules is that -bareword is equivalent
189       to the string "-bareword".  If, however, the string begins with a non-
190       alphabetic character (excluding "+" or "-"), Perl will attempt to
191       convert the string to a numeric and the arithmetic negation is
192       performed. If the string cannot be cleanly converted to a numeric, Perl
193       will give the warning Argument "the string" isn't numeric in negation
194       (-) at ....
195
196       Unary "~" performs bitwise negation, i.e., 1's complement.  For
197       example, "0666 & ~027" is 0640.  (See also "Integer Arithmetic" and
198       "Bitwise String Operators".)  Note that the width of the result is
199       platform-dependent: ~0 is 32 bits wide on a 32-bit platform, but 64
200       bits wide on a 64-bit platform, so if you are expecting a certain bit
201       width, remember to use the & operator to mask off the excess bits.
202
203       Unary "+" has no effect whatsoever, even on strings.  It is useful
204       syntactically for separating a function name from a parenthesized
205       expression that would otherwise be interpreted as the complete list of
206       function arguments.  (See examples above under "Terms and List
207       Operators (Leftward)".)
208
209       Unary "\" creates a reference to whatever follows it.  See perlreftut
210       and perlref.  Do not confuse this behavior with the behavior of
211       backslash within a string, although both forms do convey the notion of
212       protecting the next thing from interpolation.
213
214   Binding Operators
215       Binary "=~" binds a scalar expression to a pattern match.  Certain
216       operations search or modify the string $_ by default.  This operator
217       makes that kind of operation work on some other string.  The right
218       argument is a search pattern, substitution, or transliteration.  The
219       left argument is what is supposed to be searched, substituted, or
220       transliterated instead of the default $_.  When used in scalar context,
221       the return value generally indicates the success of the operation.
222       Behavior in list context depends on the particular operator.  See
223       "Regexp Quote-Like Operators" for details and perlretut for examples
224       using these operators.
225
226       If the right argument is an expression rather than a search pattern,
227       substitution, or transliteration, it is interpreted as a search pattern
228       at run time. Note that this means that its contents will be
229       interpolated twice, so
230
231         '\\' =~ q'\\';
232
233       is not ok, as the regex engine will end up trying to compile the
234       pattern "\", which it will consider a syntax error.
235
236       Binary "!~" is just like "=~" except the return value is negated in the
237       logical sense.
238
239   Multiplicative Operators
240       Binary "*" multiplies two numbers.
241
242       Binary "/" divides two numbers.
243
244       Binary "%" is the modulo operator, which computes the division
245       remainder of its first argument with respect to its second argument.
246       Given integer operands $a and $b: If $b is positive, then "$a % $b" is
247       $a minus the largest multiple of $b less than or equal to $a.  If $b is
248       negative, then "$a % $b" is $a minus the smallest multiple of $b that
249       is not less than $a (i.e. the result will be less than or equal to
250       zero).  If the operands $a and $b are floating point values and the
251       absolute value of $b (that is "abs($b)") is less than "(UV_MAX + 1)",
252       only the integer portion of $a and $b will be used in the operation
253       (Note: here "UV_MAX" means the maximum of the unsigned integer type).
254       If the absolute value of the right operand ("abs($b)") is greater than
255       or equal to "(UV_MAX + 1)", "%" computes the floating-point remainder
256       $r in the equation "($r = $a - $i*$b)" where $i is a certain integer
257       that makes $r have the same sign as the right operand $b (not as the
258       left operand $a like C function "fmod()") and the absolute value less
259       than that of $b.  Note that when "use integer" is in scope, "%" gives
260       you direct access to the modulo operator as implemented by your C
261       compiler.  This operator is not as well defined for negative operands,
262       but it will execute faster.
263
264       Binary "x" is the repetition operator.  In scalar context or if the
265       left operand is not enclosed in parentheses, it returns a string
266       consisting of the left operand repeated the number of times specified
267       by the right operand.  In list context, if the left operand is enclosed
268       in parentheses or is a list formed by "qw/STRING/", it repeats the
269       list.  If the right operand is zero or negative, it returns an empty
270       string or an empty list, depending on the context.
271
272           print '-' x 80;             # print row of dashes
273
274           print "\t" x ($tab/8), ' ' x ($tab%8);      # tab over
275
276           @ones = (1) x 80;           # a list of 80 1's
277           @ones = (5) x @ones;        # set all elements to 5
278
279   Additive Operators
280       Binary "+" returns the sum of two numbers.
281
282       Binary "-" returns the difference of two numbers.
283
284       Binary "." concatenates two strings.
285
286   Shift Operators
287       Binary "<<" returns the value of its left argument shifted left by the
288       number of bits specified by the right argument.  Arguments should be
289       integers.  (See also "Integer Arithmetic".)
290
291       Binary ">>" returns the value of its left argument shifted right by the
292       number of bits specified by the right argument.  Arguments should be
293       integers.  (See also "Integer Arithmetic".)
294
295       Note that both "<<" and ">>" in Perl are implemented directly using
296       "<<" and ">>" in C.  If "use integer" (see "Integer Arithmetic") is in
297       force then signed C integers are used, else unsigned C integers are
298       used.  Either way, the implementation isn't going to generate results
299       larger than the size of the integer type Perl was built with (32 bits
300       or 64 bits).
301
302       The result of overflowing the range of the integers is undefined
303       because it is undefined also in C.  In other words, using 32-bit
304       integers, "1 << 32" is undefined.  Shifting by a negative number of
305       bits is also undefined.
306
307   Named Unary Operators
308       The various named unary operators are treated as functions with one
309       argument, with optional parentheses.
310
311       If any list operator (print(), etc.) or any unary operator (chdir(),
312       etc.)  is followed by a left parenthesis as the next token, the
313       operator and arguments within parentheses are taken to be of highest
314       precedence, just like a normal function call.  For example, because
315       named unary operators are higher precedence than ||:
316
317           chdir $foo    || die;       # (chdir $foo) || die
318           chdir($foo)   || die;       # (chdir $foo) || die
319           chdir ($foo)  || die;       # (chdir $foo) || die
320           chdir +($foo) || die;       # (chdir $foo) || die
321
322       but, because * is higher precedence than named operators:
323
324           chdir $foo * 20;    # chdir ($foo * 20)
325           chdir($foo) * 20;   # (chdir $foo) * 20
326           chdir ($foo) * 20;  # (chdir $foo) * 20
327           chdir +($foo) * 20; # chdir ($foo * 20)
328
329           rand 10 * 20;       # rand (10 * 20)
330           rand(10) * 20;      # (rand 10) * 20
331           rand (10) * 20;     # (rand 10) * 20
332           rand +(10) * 20;    # rand (10 * 20)
333
334       Regarding precedence, the filetest operators, like "-f", "-M", etc. are
335       treated like named unary operators, but they don't follow this
336       functional parenthesis rule.  That means, for example, that
337       "-f($file).".bak"" is equivalent to "-f "$file.bak"".
338
339       See also "Terms and List Operators (Leftward)".
340
341   Relational Operators
342       Binary "<" returns true if the left argument is numerically less than
343       the right argument.
344
345       Binary ">" returns true if the left argument is numerically greater
346       than the right argument.
347
348       Binary "<=" returns true if the left argument is numerically less than
349       or equal to the right argument.
350
351       Binary ">=" returns true if the left argument is numerically greater
352       than or equal to the right argument.
353
354       Binary "lt" returns true if the left argument is stringwise less than
355       the right argument.
356
357       Binary "gt" returns true if the left argument is stringwise greater
358       than the right argument.
359
360       Binary "le" returns true if the left argument is stringwise less than
361       or equal to the right argument.
362
363       Binary "ge" returns true if the left argument is stringwise greater
364       than or equal to the right argument.
365
366   Equality Operators
367       Binary "==" returns true if the left argument is numerically equal to
368       the right argument.
369
370       Binary "!=" returns true if the left argument is numerically not equal
371       to the right argument.
372
373       Binary "<=>" returns -1, 0, or 1 depending on whether the left argument
374       is numerically less than, equal to, or greater than the right argument.
375       If your platform supports NaNs (not-a-numbers) as numeric values, using
376       them with "<=>" returns undef.  NaN is not "<", "==", ">", "<=" or ">="
377       anything (even NaN), so those 5 return false. NaN != NaN returns true,
378       as does NaN != anything else. If your platform doesn't support NaNs
379       then NaN is just a string with numeric value 0.
380
381           perl -le '$a = "NaN"; print "No NaN support here" if $a == $a'
382           perl -le '$a = "NaN"; print "NaN support here" if $a != $a'
383
384       Binary "eq" returns true if the left argument is stringwise equal to
385       the right argument.
386
387       Binary "ne" returns true if the left argument is stringwise not equal
388       to the right argument.
389
390       Binary "cmp" returns -1, 0, or 1 depending on whether the left argument
391       is stringwise less than, equal to, or greater than the right argument.
392
393       Binary "~~" does a smart match between its arguments. Smart matching is
394       described in "Smart matching in detail" in perlsyn.
395
396       "lt", "le", "ge", "gt" and "cmp" use the collation (sort) order
397       specified by the current locale if "use locale" is in effect.  See
398       perllocale.
399
400   Bitwise And
401       Binary "&" returns its operands ANDed together bit by bit.  (See also
402       "Integer Arithmetic" and "Bitwise String Operators".)
403
404       Note that "&" has lower priority than relational operators, so for
405       example the brackets are essential in a test like
406
407               print "Even\n" if ($x & 1) == 0;
408
409   Bitwise Or and Exclusive Or
410       Binary "|" returns its operands ORed together bit by bit.  (See also
411       "Integer Arithmetic" and "Bitwise String Operators".)
412
413       Binary "^" returns its operands XORed together bit by bit.  (See also
414       "Integer Arithmetic" and "Bitwise String Operators".)
415
416       Note that "|" and "^" have lower priority than relational operators, so
417       for example the brackets are essential in a test like
418
419               print "false\n" if (8 | 2) != 10;
420
421   C-style Logical And
422       Binary "&&" performs a short-circuit logical AND operation.  That is,
423       if the left operand is false, the right operand is not even evaluated.
424       Scalar or list context propagates down to the right operand if it is
425       evaluated.
426
427   C-style Logical Or
428       Binary "||" performs a short-circuit logical OR operation.  That is, if
429       the left operand is true, the right operand is not even evaluated.
430       Scalar or list context propagates down to the right operand if it is
431       evaluated.
432
433   C-style Logical Defined-Or
434       Although it has no direct equivalent in C, Perl's "//" operator is
435       related to its C-style or.  In fact, it's exactly the same as "||",
436       except that it tests the left hand side's definedness instead of its
437       truth.  Thus, "$a // $b" is similar to "defined($a) || $b" (except that
438       it returns the value of $a rather than the value of "defined($a)") and
439       is exactly equivalent to "defined($a) ? $a : $b".  This is very useful
440       for providing default values for variables.  If you actually want to
441       test if at least one of $a and $b is defined, use "defined($a // $b)".
442
443       The "||", "//" and "&&" operators return the last value evaluated
444       (unlike C's "||" and "&&", which return 0 or 1). Thus, a reasonably
445       portable way to find out the home directory might be:
446
447           $home = $ENV{'HOME'} // $ENV{'LOGDIR'} //
448               (getpwuid($<))[7] // die "You're homeless!\n";
449
450       In particular, this means that you shouldn't use this for selecting
451       between two aggregates for assignment:
452
453           @a = @b || @c;              # this is wrong
454           @a = scalar(@b) || @c;      # really meant this
455           @a = @b ? @b : @c;          # this works fine, though
456
457       As more readable alternatives to "&&" and "||" when used for control
458       flow, Perl provides the "and" and "or" operators (see below).  The
459       short-circuit behavior is identical.  The precedence of "and" and "or"
460       is much lower, however, so that you can safely use them after a list
461       operator without the need for parentheses:
462
463           unlink "alpha", "beta", "gamma"
464                   or gripe(), next LINE;
465
466       With the C-style operators that would have been written like this:
467
468           unlink("alpha", "beta", "gamma")
469                   || (gripe(), next LINE);
470
471       Using "or" for assignment is unlikely to do what you want; see below.
472
473   Range Operators
474       Binary ".." is the range operator, which is really two different
475       operators depending on the context.  In list context, it returns a list
476       of values counting (up by ones) from the left value to the right value.
477       If the left value is greater than the right value then it returns the
478       empty list.  The range operator is useful for writing "foreach (1..10)"
479       loops and for doing slice operations on arrays. In the current
480       implementation, no temporary array is created when the range operator
481       is used as the expression in "foreach" loops, but older versions of
482       Perl might burn a lot of memory when you write something like this:
483
484           for (1 .. 1_000_000) {
485               # code
486           }
487
488       The range operator also works on strings, using the magical auto-
489       increment, see below.
490
491       In scalar context, ".." returns a boolean value.  The operator is
492       bistable, like a flip-flop, and emulates the line-range (comma)
493       operator of sed, awk, and various editors.  Each ".." operator
494       maintains its own boolean state.  It is false as long as its left
495       operand is false.  Once the left operand is true, the range operator
496       stays true until the right operand is true, AFTER which the range
497       operator becomes false again.  It doesn't become false till the next
498       time the range operator is evaluated.  It can test the right operand
499       and become false on the same evaluation it became true (as in awk), but
500       it still returns true once.  If you don't want it to test the right
501       operand till the next evaluation, as in sed, just use three dots
502       ("...") instead of two.  In all other regards, "..." behaves just like
503       ".." does.
504
505       The right operand is not evaluated while the operator is in the "false"
506       state, and the left operand is not evaluated while the operator is in
507       the "true" state.  The precedence is a little lower than || and &&.
508       The value returned is either the empty string for false, or a sequence
509       number (beginning with 1) for true.  The sequence number is reset for
510       each range encountered.  The final sequence number in a range has the
511       string "E0" appended to it, which doesn't affect its numeric value, but
512       gives you something to search for if you want to exclude the endpoint.
513       You can exclude the beginning point by waiting for the sequence number
514       to be greater than 1.
515
516       If either operand of scalar ".." is a constant expression, that operand
517       is considered true if it is equal ("==") to the current input line
518       number (the $. variable).
519
520       To be pedantic, the comparison is actually "int(EXPR) == int(EXPR)",
521       but that is only an issue if you use a floating point expression; when
522       implicitly using $. as described in the previous paragraph, the
523       comparison is "int(EXPR) == int($.)" which is only an issue when $.  is
524       set to a floating point value and you are not reading from a file.
525       Furthermore, "span" .. "spat" or "2.18 .. 3.14" will not do what you
526       want in scalar context because each of the operands are evaluated using
527       their integer representation.
528
529       Examples:
530
531       As a scalar operator:
532
533           if (101 .. 200) { print; } # print 2nd hundred lines, short for
534                                      #   if ($. == 101 .. $. == 200) { print; }
535
536           next LINE if (1 .. /^$/);  # skip header lines, short for
537                                      #   next LINE if ($. == 1 .. /^$/);
538                                      # (typically in a loop labeled LINE)
539
540           s/^/> / if (/^$/ .. eof());  # quote body
541
542           # parse mail messages
543           while (<>) {
544               $in_header =   1  .. /^$/;
545               $in_body   = /^$/ .. eof;
546               if ($in_header) {
547                   # do something
548               } else { # in body
549                   # do something else
550               }
551           } continue {
552               close ARGV if eof;             # reset $. each file
553           }
554
555       Here's a simple example to illustrate the difference between the two
556       range operators:
557
558           @lines = ("   - Foo",
559                     "01 - Bar",
560                     "1  - Baz",
561                     "   - Quux");
562
563           foreach (@lines) {
564               if (/0/ .. /1/) {
565                   print "$_\n";
566               }
567           }
568
569       This program will print only the line containing "Bar". If the range
570       operator is changed to "...", it will also print the "Baz" line.
571
572       And now some examples as a list operator:
573
574           for (101 .. 200) { print; } # print $_ 100 times
575           @foo = @foo[0 .. $#foo];    # an expensive no-op
576           @foo = @foo[$#foo-4 .. $#foo];      # slice last 5 items
577
578       The range operator (in list context) makes use of the magical auto-
579       increment algorithm if the operands are strings.  You can say
580
581           @alphabet = ('A' .. 'Z');
582
583       to get all normal letters of the English alphabet, or
584
585           $hexdigit = (0 .. 9, 'a' .. 'f')[$num & 15];
586
587       to get a hexadecimal digit, or
588
589           @z2 = ('01' .. '31');  print $z2[$mday];
590
591       to get dates with leading zeros.
592
593       If the final value specified is not in the sequence that the magical
594       increment would produce, the sequence goes until the next value would
595       be longer than the final value specified.
596
597       If the initial value specified isn't part of a magical increment
598       sequence (that is, a non-empty string matching "/^[a-zA-Z]*[0-9]*\z/"),
599       only the initial value will be returned.  So the following will only
600       return an alpha:
601
602           use charnames 'greek';
603           my @greek_small =  ("\N{alpha}" .. "\N{omega}");
604
605       To get lower-case greek letters, use this instead:
606
607           my @greek_small =  map { chr } ( ord("\N{alpha}") .. ord("\N{omega}") );
608
609       Because each operand is evaluated in integer form, "2.18 .. 3.14" will
610       return two elements in list context.
611
612           @list = (2.18 .. 3.14); # same as @list = (2 .. 3);
613
614   Conditional Operator
615       Ternary "?:" is the conditional operator, just as in C.  It works much
616       like an if-then-else.  If the argument before the ? is true, the
617       argument before the : is returned, otherwise the argument after the :
618       is returned.  For example:
619
620           printf "I have %d dog%s.\n", $n,
621                   ($n == 1) ? '' : "s";
622
623       Scalar or list context propagates downward into the 2nd or 3rd
624       argument, whichever is selected.
625
626           $a = $ok ? $b : $c;  # get a scalar
627           @a = $ok ? @b : @c;  # get an array
628           $a = $ok ? @b : @c;  # oops, that's just a count!
629
630       The operator may be assigned to if both the 2nd and 3rd arguments are
631       legal lvalues (meaning that you can assign to them):
632
633           ($a_or_b ? $a : $b) = $c;
634
635       Because this operator produces an assignable result, using assignments
636       without parentheses will get you in trouble.  For example, this:
637
638           $a % 2 ? $a += 10 : $a += 2
639
640       Really means this:
641
642           (($a % 2) ? ($a += 10) : $a) += 2
643
644       Rather than this:
645
646           ($a % 2) ? ($a += 10) : ($a += 2)
647
648       That should probably be written more simply as:
649
650           $a += ($a % 2) ? 10 : 2;
651
652   Assignment Operators
653       "=" is the ordinary assignment operator.
654
655       Assignment operators work as in C.  That is,
656
657           $a += 2;
658
659       is equivalent to
660
661           $a = $a + 2;
662
663       although without duplicating any side effects that dereferencing the
664       lvalue might trigger, such as from tie().  Other assignment operators
665       work similarly.  The following are recognized:
666
667           **=    +=    *=    &=    <<=    &&=
668                  -=    /=    |=    >>=    ||=
669                  .=    %=    ^=           //=
670                        x=
671
672       Although these are grouped by family, they all have the precedence of
673       assignment.
674
675       Unlike in C, the scalar assignment operator produces a valid lvalue.
676       Modifying an assignment is equivalent to doing the assignment and then
677       modifying the variable that was assigned to.  This is useful for
678       modifying a copy of something, like this:
679
680           ($tmp = $global) =~ tr [A-Z] [a-z];
681
682       Likewise,
683
684           ($a += 2) *= 3;
685
686       is equivalent to
687
688           $a += 2;
689           $a *= 3;
690
691       Similarly, a list assignment in list context produces the list of
692       lvalues assigned to, and a list assignment in scalar context returns
693       the number of elements produced by the expression on the right hand
694       side of the assignment.
695
696   Comma Operator
697       Binary "," is the comma operator.  In scalar context it evaluates its
698       left argument, throws that value away, then evaluates its right
699       argument and returns that value.  This is just like C's comma operator.
700
701       In list context, it's just the list argument separator, and inserts
702       both its arguments into the list.  These arguments are also evaluated
703       from left to right.
704
705       The "=>" operator is a synonym for the comma except that it causes its
706       left operand to be interpreted as a string if it begins with a letter
707       or underscore and is composed only of letters, digits and underscores.
708       This includes operands that might otherwise be interpreted as
709       operators, constants, single number v-strings or function calls. If in
710       doubt about this behaviour, the left operand can be quoted explicitly.
711
712       Otherwise, the "=>" operator behaves exactly as the comma operator or
713       list argument separator, according to context.
714
715       For example:
716
717           use constant FOO => "something";
718
719           my %h = ( FOO => 23 );
720
721       is equivalent to:
722
723           my %h = ("FOO", 23);
724
725       It is NOT:
726
727           my %h = ("something", 23);
728
729       The "=>" operator is helpful in documenting the correspondence between
730       keys and values in hashes, and other paired elements in lists.
731
732               %hash = ( $key => $value );
733               login( $username => $password );
734
735   List Operators (Rightward)
736       On the right side of a list operator, it has very low precedence, such
737       that it controls all comma-separated expressions found there.  The only
738       operators with lower precedence are the logical operators "and", "or",
739       and "not", which may be used to evaluate calls to list operators
740       without the need for extra parentheses:
741
742           open HANDLE, "filename"
743               or die "Can't open: $!\n";
744
745       See also discussion of list operators in "Terms and List Operators
746       (Leftward)".
747
748   Logical Not
749       Unary "not" returns the logical negation of the expression to its
750       right.  It's the equivalent of "!" except for the very low precedence.
751
752   Logical And
753       Binary "and" returns the logical conjunction of the two surrounding
754       expressions.  It's equivalent to && except for the very low precedence.
755       This means that it short-circuits: i.e., the right expression is
756       evaluated only if the left expression is true.
757
758   Logical or, Defined or, and Exclusive Or
759       Binary "or" returns the logical disjunction of the two surrounding
760       expressions.  It's equivalent to || except for the very low precedence.
761       This makes it useful for control flow
762
763           print FH $data              or die "Can't write to FH: $!";
764
765       This means that it short-circuits: i.e., the right expression is
766       evaluated only if the left expression is false.  Due to its precedence,
767       you should probably avoid using this for assignment, only for control
768       flow.
769
770           $a = $b or $c;              # bug: this is wrong
771           ($a = $b) or $c;            # really means this
772           $a = $b || $c;              # better written this way
773
774       However, when it's a list-context assignment and you're trying to use
775       "||" for control flow, you probably need "or" so that the assignment
776       takes higher precedence.
777
778           @info = stat($file) || die;     # oops, scalar sense of stat!
779           @info = stat($file) or die;     # better, now @info gets its due
780
781       Then again, you could always use parentheses.
782
783       Binary "xor" returns the exclusive-OR of the two surrounding
784       expressions.  It cannot short circuit, of course.
785
786   C Operators Missing From Perl
787       Here is what C has that Perl doesn't:
788
789       unary & Address-of operator.  (But see the "\" operator for taking a
790               reference.)
791
792       unary * Dereference-address operator. (Perl's prefix dereferencing
793               operators are typed: $, @, %, and &.)
794
795       (TYPE)  Type-casting operator.
796
797   Quote and Quote-like Operators
798       While we usually think of quotes as literal values, in Perl they
799       function as operators, providing various kinds of interpolating and
800       pattern matching capabilities.  Perl provides customary quote
801       characters for these behaviors, but also provides a way for you to
802       choose your quote character for any of them.  In the following table, a
803       "{}" represents any pair of delimiters you choose.
804
805           Customary  Generic        Meaning        Interpolates
806               ''       q{}          Literal             no
807               ""      qq{}          Literal             yes
808               ``      qx{}          Command             yes*
809                       qw{}         Word list            no
810               //       m{}       Pattern match          yes*
811                       qr{}          Pattern             yes*
812                        s{}{}      Substitution          yes*
813                       tr{}{}    Transliteration         no (but see below)
814               <<EOF                 here-doc            yes*
815
816               * unless the delimiter is ''.
817
818       Non-bracketing delimiters use the same character fore and aft, but the
819       four sorts of brackets (round, angle, square, curly) will all nest,
820       which means that
821
822               q{foo{bar}baz}
823
824       is the same as
825
826               'foo{bar}baz'
827
828       Note, however, that this does not always work for quoting Perl code:
829
830               $s = q{ if($a eq "}") ... }; # WRONG
831
832       is a syntax error. The "Text::Balanced" module (from CPAN, and starting
833       from Perl 5.8 part of the standard distribution) is able to do this
834       properly.
835
836       There can be whitespace between the operator and the quoting
837       characters, except when "#" is being used as the quoting character.
838       "q#foo#" is parsed as the string "foo", while "q #foo#" is the operator
839       "q" followed by a comment.  Its argument will be taken from the next
840       line.  This allows you to write:
841
842           s {foo}  # Replace foo
843             {bar}  # with bar.
844
845       The following escape sequences are available in constructs that
846       interpolate and in transliterations.
847
848           \t          tab             (HT, TAB)
849           \n          newline         (NL)
850           \r          return          (CR)
851           \f          form feed       (FF)
852           \b          backspace       (BS)
853           \a          alarm (bell)    (BEL)
854           \e          escape          (ESC)
855           \033        octal char      (example: ESC)
856           \x1b        hex char        (example: ESC)
857           \x{263a}    wide hex char   (example: SMILEY)
858           \c[         control char    (example: ESC)
859           \N{name}    named Unicode character
860
861       The character following "\c" is mapped to some other character by
862       converting letters to upper case and then (on ASCII systems) by
863       inverting the 7th bit (0x40). The most interesting range is from '@' to
864       '_' (0x40 through 0x5F), resulting in a control character from 0x00
865       through 0x1F. A '?' maps to the DEL character. On EBCDIC systems only
866       '@', the letters, '[', '\', ']', '^', '_' and '?' will work, resulting
867       in 0x00 through 0x1F and 0x7F.
868
869       NOTE: Unlike C and other languages, Perl has no \v escape sequence for
870       the vertical tab (VT - ASCII 11), but you may use "\ck" or "\x0b".
871
872       The following escape sequences are available in constructs that
873       interpolate but not in transliterations.
874
875           \l          lowercase next char
876           \u          uppercase next char
877           \L          lowercase till \E
878           \U          uppercase till \E
879           \E          end case modification
880           \Q          quote non-word characters till \E
881
882       If "use locale" is in effect, the case map used by "\l", "\L", "\u" and
883       "\U" is taken from the current locale.  See perllocale.  If Unicode
884       (for example, "\N{}" or wide hex characters of 0x100 or beyond) is
885       being used, the case map used by "\l", "\L", "\u" and "\U" is as
886       defined by Unicode.  For documentation of "\N{name}", see charnames.
887
888       All systems use the virtual "\n" to represent a line terminator, called
889       a "newline".  There is no such thing as an unvarying, physical newline
890       character.  It is only an illusion that the operating system, device
891       drivers, C libraries, and Perl all conspire to preserve.  Not all
892       systems read "\r" as ASCII CR and "\n" as ASCII LF.  For example, on a
893       Mac, these are reversed, and on systems without line terminator,
894       printing "\n" may emit no actual data.  In general, use "\n" when you
895       mean a "newline" for your system, but use the literal ASCII when you
896       need an exact character.  For example, most networking protocols expect
897       and prefer a CR+LF ("\015\012" or "\cM\cJ") for line terminators, and
898       although they often accept just "\012", they seldom tolerate just
899       "\015".  If you get in the habit of using "\n" for networking, you may
900       be burned some day.
901
902       For constructs that do interpolate, variables beginning with ""$"" or
903       ""@"" are interpolated.  Subscripted variables such as $a[3] or
904       "$href->{key}[0]" are also interpolated, as are array and hash slices.
905       But method calls such as "$obj->meth" are not.
906
907       Interpolating an array or slice interpolates the elements in order,
908       separated by the value of $", so is equivalent to interpolating "join
909       $", @array".    "Punctuation" arrays such as "@*" are only interpolated
910       if the name is enclosed in braces "@{*}", but special arrays @_, "@+",
911       and "@-" are interpolated, even without braces.
912
913       You cannot include a literal "$" or "@" within a "\Q" sequence.  An
914       unescaped "$" or "@" interpolates the corresponding variable, while
915       escaping will cause the literal string "\$" to be inserted.  You'll
916       need to write something like "m/\Quser\E\@\Qhost/".
917
918       Patterns are subject to an additional level of interpretation as a
919       regular expression.  This is done as a second pass, after variables are
920       interpolated, so that regular expressions may be incorporated into the
921       pattern from the variables.  If this is not what you want, use "\Q" to
922       interpolate a variable literally.
923
924       Apart from the behavior described above, Perl does not expand multiple
925       levels of interpolation.  In particular, contrary to the expectations
926       of shell programmers, back-quotes do NOT interpolate within double
927       quotes, nor do single quotes impede evaluation of variables when used
928       within double quotes.
929
930   Regexp Quote-Like Operators
931       Here are the quote-like operators that apply to pattern matching and
932       related activities.
933
934       qr/STRING/msixpo
935               This operator quotes (and possibly compiles) its STRING as a
936               regular expression.  STRING is interpolated the same way as
937               PATTERN in "m/PATTERN/".  If "'" is used as the delimiter, no
938               interpolation is done.  Returns a Perl value which may be used
939               instead of the corresponding "/STRING/msixpo" expression. The
940               returned value is a normalized version of the original pattern.
941               It magically differs from a string containing the same
942               characters: "ref(qr/x/)" returns "Regexp", even though
943               dereferencing the result returns undef.
944
945               For example,
946
947                   $rex = qr/my.STRING/is;
948                   print $rex;                 # prints (?si-xm:my.STRING)
949                   s/$rex/foo/;
950
951               is equivalent to
952
953                   s/my.STRING/foo/is;
954
955               The result may be used as a subpattern in a match:
956
957                   $re = qr/$pattern/;
958                   $string =~ /foo${re}bar/;   # can be interpolated in other patterns
959                   $string =~ $re;             # or used standalone
960                   $string =~ /$re/;           # or this way
961
962               Since Perl may compile the pattern at the moment of execution
963               of qr() operator, using qr() may have speed advantages in some
964               situations, notably if the result of qr() is used standalone:
965
966                   sub match {
967                       my $patterns = shift;
968                       my @compiled = map qr/$_/i, @$patterns;
969                       grep {
970                           my $success = 0;
971                           foreach my $pat (@compiled) {
972                               $success = 1, last if /$pat/;
973                           }
974                           $success;
975                       } @_;
976                   }
977
978               Precompilation of the pattern into an internal representation
979               at the moment of qr() avoids a need to recompile the pattern
980               every time a match "/$pat/" is attempted.  (Perl has many other
981               internal optimizations, but none would be triggered in the
982               above example if we did not use qr() operator.)
983
984               Options are:
985
986                   m   Treat string as multiple lines.
987                   s   Treat string as single line. (Make . match a newline)
988                   i   Do case-insensitive pattern matching.
989                   x   Use extended regular expressions.
990                   p   When matching preserve a copy of the matched string so
991                       that ${^PREMATCH}, ${^MATCH}, ${^POSTMATCH} will be defined.
992                   o   Compile pattern only once.
993
994               If a precompiled pattern is embedded in a larger pattern then
995               the effect of 'msixp' will be propagated appropriately.  The
996               effect of the 'o' modifier has is not propagated, being
997               restricted to those patterns explicitly using it.
998
999               See perlre for additional information on valid syntax for
1000               STRING, and for a detailed look at the semantics of regular
1001               expressions.
1002
1003       m/PATTERN/msixpogc
1004       /PATTERN/msixpogc
1005               Searches a string for a pattern match, and in scalar context
1006               returns true if it succeeds, false if it fails.  If no string
1007               is specified via the "=~" or "!~" operator, the $_ string is
1008               searched.  (The string specified with "=~" need not be an
1009               lvalue--it may be the result of an expression evaluation, but
1010               remember the "=~" binds rather tightly.)  See also perlre.  See
1011               perllocale for discussion of additional considerations that
1012               apply when "use locale" is in effect.
1013
1014               Options are as described in "qr//"; in addition, the following
1015               match process modifiers are available:
1016
1017                   g   Match globally, i.e., find all occurrences.
1018                   c   Do not reset search position on a failed match when /g is in effect.
1019
1020               If "/" is the delimiter then the initial "m" is optional.  With
1021               the "m" you can use any pair of non-alphanumeric, non-
1022               whitespace characters as delimiters.  This is particularly
1023               useful for matching path names that contain "/", to avoid LTS
1024               (leaning toothpick syndrome).  If "?" is the delimiter, then
1025               the match-only-once rule of "?PATTERN?" applies.  If "'" is the
1026               delimiter, no interpolation is performed on the PATTERN.
1027
1028               PATTERN may contain variables, which will be interpolated (and
1029               the pattern recompiled) every time the pattern search is
1030               evaluated, except for when the delimiter is a single quote.
1031               (Note that $(, $), and $| are not interpolated because they
1032               look like end-of-string tests.)  If you want such a pattern to
1033               be compiled only once, add a "/o" after the trailing delimiter.
1034               This avoids expensive run-time recompilations, and is useful
1035               when the value you are interpolating won't change over the life
1036               of the script.  However, mentioning "/o" constitutes a promise
1037               that you won't change the variables in the pattern.  If you
1038               change them, Perl won't even notice.  See also "STRING/msixpo""
1039               in "qr.
1040
1041       The empty pattern //
1042               If the PATTERN evaluates to the empty string, the last
1043               successfully matched regular expression is used instead. In
1044               this case, only the "g" and "c" flags on the empty pattern is
1045               honoured - the other flags are taken from the original pattern.
1046               If no match has previously succeeded, this will (silently) act
1047               instead as a genuine empty pattern (which will always match).
1048
1049               Note that it's possible to confuse Perl into thinking "//" (the
1050               empty regex) is really "//" (the defined-or operator).  Perl is
1051               usually pretty good about this, but some pathological cases
1052               might trigger this, such as "$a///" (is that "($a) / (//)" or
1053               "$a // /"?) and "print $fh //" ("print $fh(//" or "print($fh
1054               //"?).  In all of these examples, Perl will assume you meant
1055               defined-or.  If you meant the empty regex, just use parentheses
1056               or spaces to disambiguate, or even prefix the empty regex with
1057               an "m" (so "//" becomes "m//").
1058
1059       Matching in list context
1060               If the "/g" option is not used, "m//" in list context returns a
1061               list consisting of the subexpressions matched by the
1062               parentheses in the pattern, i.e., ($1, $2, $3...).  (Note that
1063               here $1 etc. are also set, and that this differs from Perl 4's
1064               behavior.)  When there are no parentheses in the pattern, the
1065               return value is the list "(1)" for success.  With or without
1066               parentheses, an empty list is returned upon failure.
1067
1068               Examples:
1069
1070                   open(TTY, '/dev/tty');
1071                   <TTY> =~ /^y/i && foo();    # do foo if desired
1072
1073                   if (/Version: *([0-9.]*)/) { $version = $1; }
1074
1075                   next if m#^/usr/spool/uucp#;
1076
1077                   # poor man's grep
1078                   $arg = shift;
1079                   while (<>) {
1080                       print if /$arg/o;       # compile only once
1081                   }
1082
1083                   if (($F1, $F2, $Etc) = ($foo =~ /^(\S+)\s+(\S+)\s*(.*)/))
1084
1085               This last example splits $foo into the first two words and the
1086               remainder of the line, and assigns those three fields to $F1,
1087               $F2, and $Etc.  The conditional is true if any variables were
1088               assigned, i.e., if the pattern matched.
1089
1090               The "/g" modifier specifies global pattern matching--that is,
1091               matching as many times as possible within the string.  How it
1092               behaves depends on the context.  In list context, it returns a
1093               list of the substrings matched by any capturing parentheses in
1094               the regular expression.  If there are no parentheses, it
1095               returns a list of all the matched strings, as if there were
1096               parentheses around the whole pattern.
1097
1098               In scalar context, each execution of "m//g" finds the next
1099               match, returning true if it matches, and false if there is no
1100               further match.  The position after the last match can be read
1101               or set using the pos() function; see "pos" in perlfunc.   A
1102               failed match normally resets the search position to the
1103               beginning of the string, but you can avoid that by adding the
1104               "/c" modifier (e.g. "m//gc").  Modifying the target string also
1105               resets the search position.
1106
1107       \G assertion
1108               You can intermix "m//g" matches with "m/\G.../g", where "\G" is
1109               a zero-width assertion that matches the exact position where
1110               the previous "m//g", if any, left off.  Without the "/g"
1111               modifier, the "\G" assertion still anchors at pos(), but the
1112               match is of course only attempted once.  Using "\G" without
1113               "/g" on a target string that has not previously had a "/g"
1114               match applied to it is the same as using the "\A" assertion to
1115               match the beginning of the string.  Note also that, currently,
1116               "\G" is only properly supported when anchored at the very
1117               beginning of the pattern.
1118
1119               Examples:
1120
1121                   # list context
1122                   ($one,$five,$fifteen) = (`uptime` =~ /(\d+\.\d+)/g);
1123
1124                   # scalar context
1125                   $/ = "";
1126                   while (defined($paragraph = <>)) {
1127                       while ($paragraph =~ /[a-z]['")]*[.!?]+['")]*\s/g) {
1128                           $sentences++;
1129                       }
1130                   }
1131                   print "$sentences\n";
1132
1133                   # using m//gc with \G
1134                   $_ = "ppooqppqq";
1135                   while ($i++ < 2) {
1136                       print "1: '";
1137                       print $1 while /(o)/gc; print "', pos=", pos, "\n";
1138                       print "2: '";
1139                       print $1 if /\G(q)/gc;  print "', pos=", pos, "\n";
1140                       print "3: '";
1141                       print $1 while /(p)/gc; print "', pos=", pos, "\n";
1142                   }
1143                   print "Final: '$1', pos=",pos,"\n" if /\G(.)/;
1144
1145               The last example should print:
1146
1147                   1: 'oo', pos=4
1148                   2: 'q', pos=5
1149                   3: 'pp', pos=7
1150                   1: '', pos=7
1151                   2: 'q', pos=8
1152                   3: '', pos=8
1153                   Final: 'q', pos=8
1154
1155               Notice that the final match matched "q" instead of "p", which a
1156               match without the "\G" anchor would have done. Also note that
1157               the final match did not update "pos" -- "pos" is only updated
1158               on a "/g" match. If the final match did indeed match "p", it's
1159               a good bet that you're running an older (pre-5.6.0) Perl.
1160
1161               A useful idiom for "lex"-like scanners is "/\G.../gc".  You can
1162               combine several regexps like this to process a string part-by-
1163               part, doing different actions depending on which regexp
1164               matched.  Each regexp tries to match where the previous one
1165               leaves off.
1166
1167                $_ = <<'EOL';
1168                     $url = URI::URL->new( "http://www/" );   die if $url eq "xXx";
1169                EOL
1170                LOOP:
1171                   {
1172                     print(" digits"),         redo LOOP if /\G\d+\b[,.;]?\s*/gc;
1173                     print(" lowercase"),      redo LOOP if /\G[a-z]+\b[,.;]?\s*/gc;
1174                     print(" UPPERCASE"),      redo LOOP if /\G[A-Z]+\b[,.;]?\s*/gc;
1175                     print(" Capitalized"),    redo LOOP if /\G[A-Z][a-z]+\b[,.;]?\s*/gc;
1176                     print(" MiXeD"),          redo LOOP if /\G[A-Za-z]+\b[,.;]?\s*/gc;
1177                     print(" alphanumeric"),   redo LOOP if /\G[A-Za-z0-9]+\b[,.;]?\s*/gc;
1178                     print(" line-noise"),     redo LOOP if /\G[^A-Za-z0-9]+/gc;
1179                     print ". That's all!\n";
1180                   }
1181
1182               Here is the output (split into several lines):
1183
1184                line-noise lowercase line-noise lowercase UPPERCASE line-noise
1185                UPPERCASE line-noise lowercase line-noise lowercase line-noise
1186                lowercase lowercase line-noise lowercase lowercase line-noise
1187                MiXeD line-noise. That's all!
1188
1189       ?PATTERN?
1190               This is just like the "/pattern/" search, except that it
1191               matches only once between calls to the reset() operator.  This
1192               is a useful optimization when you want to see only the first
1193               occurrence of something in each file of a set of files, for
1194               instance.  Only "??"  patterns local to the current package are
1195               reset.
1196
1197                   while (<>) {
1198                       if (?^$?) {
1199                                           # blank line between header and body
1200                       }
1201                   } continue {
1202                       reset if eof;       # clear ?? status for next file
1203                   }
1204
1205               This usage is vaguely deprecated, which means it just might
1206               possibly be removed in some distant future version of Perl,
1207               perhaps somewhere around the year 2168.
1208
1209       s/PATTERN/REPLACEMENT/msixpogce
1210               Searches a string for a pattern, and if found, replaces that
1211               pattern with the replacement text and returns the number of
1212               substitutions made.  Otherwise it returns false (specifically,
1213               the empty string).
1214
1215               If no string is specified via the "=~" or "!~" operator, the $_
1216               variable is searched and modified.  (The string specified with
1217               "=~" must be scalar variable, an array element, a hash element,
1218               or an assignment to one of those, i.e., an lvalue.)
1219
1220               If the delimiter chosen is a single quote, no interpolation is
1221               done on either the PATTERN or the REPLACEMENT.  Otherwise, if
1222               the PATTERN contains a $ that looks like a variable rather than
1223               an end-of-string test, the variable will be interpolated into
1224               the pattern at run-time.  If you want the pattern compiled only
1225               once the first time the variable is interpolated, use the "/o"
1226               option.  If the pattern evaluates to the empty string, the last
1227               successfully executed regular expression is used instead.  See
1228               perlre for further explanation on these.  See perllocale for
1229               discussion of additional considerations that apply when "use
1230               locale" is in effect.
1231
1232               Options are as with m// with the addition of the following
1233               replacement specific options:
1234
1235                   e   Evaluate the right side as an expression.
1236                   ee  Evaluate the right side as a string then eval the result
1237
1238               Any non-alphanumeric, non-whitespace delimiter may replace the
1239               slashes.  If single quotes are used, no interpretation is done
1240               on the replacement string (the "/e" modifier overrides this,
1241               however).  Unlike Perl 4, Perl 5 treats backticks as normal
1242               delimiters; the replacement text is not evaluated as a command.
1243               If the PATTERN is delimited by bracketing quotes, the
1244               REPLACEMENT has its own pair of quotes, which may or may not be
1245               bracketing quotes, e.g., "s(foo)(bar)" or "s<foo>/bar/".  A
1246               "/e" will cause the replacement portion to be treated as a
1247               full-fledged Perl expression and evaluated right then and
1248               there.  It is, however, syntax checked at compile-time. A
1249               second "e" modifier will cause the replacement portion to be
1250               "eval"ed before being run as a Perl expression.
1251
1252               Examples:
1253
1254                   s/\bgreen\b/mauve/g;                # don't change wintergreen
1255
1256                   $path =~ s|/usr/bin|/usr/local/bin|;
1257
1258                   s/Login: $foo/Login: $bar/; # run-time pattern
1259
1260                   ($foo = $bar) =~ s/this/that/;      # copy first, then change
1261
1262                   $count = ($paragraph =~ s/Mister\b/Mr./g);  # get change-count
1263
1264                   $_ = 'abc123xyz';
1265                   s/\d+/$&*2/e;               # yields 'abc246xyz'
1266                   s/\d+/sprintf("%5d",$&)/e;  # yields 'abc  246xyz'
1267                   s/\w/$& x 2/eg;             # yields 'aabbcc  224466xxyyzz'
1268
1269                   s/%(.)/$percent{$1}/g;      # change percent escapes; no /e
1270                   s/%(.)/$percent{$1} || $&/ge;       # expr now, so /e
1271                   s/^=(\w+)/pod($1)/ge;       # use function call
1272
1273                   # expand variables in $_, but dynamics only, using
1274                   # symbolic dereferencing
1275                   s/\$(\w+)/${$1}/g;
1276
1277                   # Add one to the value of any numbers in the string
1278                   s/(\d+)/1 + $1/eg;
1279
1280                   # This will expand any embedded scalar variable
1281                   # (including lexicals) in $_ : First $1 is interpolated
1282                   # to the variable name, and then evaluated
1283                   s/(\$\w+)/$1/eeg;
1284
1285                   # Delete (most) C comments.
1286                   $program =~ s {
1287                       /\*     # Match the opening delimiter.
1288                       .*?     # Match a minimal number of characters.
1289                       \*/     # Match the closing delimiter.
1290                   } []gsx;
1291
1292                   s/^\s*(.*?)\s*$/$1/;        # trim whitespace in $_, expensively
1293
1294                   for ($variable) {           # trim whitespace in $variable, cheap
1295                       s/^\s+//;
1296                       s/\s+$//;
1297                   }
1298
1299                   s/([^ ]*) *([^ ]*)/$2 $1/;  # reverse 1st two fields
1300
1301               Note the use of $ instead of \ in the last example.  Unlike
1302               sed, we use the \<digit> form in only the left hand side.
1303               Anywhere else it's $<digit>.
1304
1305               Occasionally, you can't use just a "/g" to get all the changes
1306               to occur that you might want.  Here are two common cases:
1307
1308                   # put commas in the right places in an integer
1309                   1 while s/(\d)(\d\d\d)(?!\d)/$1,$2/g;
1310
1311                   # expand tabs to 8-column spacing
1312                   1 while s/\t+/' ' x (length($&)*8 - length($`)%8)/e;
1313
1314   Quote-Like Operators
1315       q/STRING/
1316       'STRING'
1317           A single-quoted, literal string.  A backslash represents a
1318           backslash unless followed by the delimiter or another backslash, in
1319           which case the delimiter or backslash is interpolated.
1320
1321               $foo = q!I said, "You said, 'She said it.'"!;
1322               $bar = q('This is it.');
1323               $baz = '\n';                # a two-character string
1324
1325       qq/STRING/
1326       "STRING"
1327           A double-quoted, interpolated string.
1328
1329               $_ .= qq
1330                (*** The previous line contains the naughty word "$1".\n)
1331                           if /\b(tcl|java|python)\b/i;      # :-)
1332               $baz = "\n";                # a one-character string
1333
1334       qx/STRING/
1335       `STRING`
1336           A string which is (possibly) interpolated and then executed as a
1337           system command with "/bin/sh" or its equivalent.  Shell wildcards,
1338           pipes, and redirections will be honored.  The collected standard
1339           output of the command is returned; standard error is unaffected.
1340           In scalar context, it comes back as a single (potentially multi-
1341           line) string, or undef if the command failed.  In list context,
1342           returns a list of lines (however you've defined lines with $/ or
1343           $INPUT_RECORD_SEPARATOR), or an empty list if the command failed.
1344
1345           Because backticks do not affect standard error, use shell file
1346           descriptor syntax (assuming the shell supports this) if you care to
1347           address this.  To capture a command's STDERR and STDOUT together:
1348
1349               $output = `cmd 2>&1`;
1350
1351           To capture a command's STDOUT but discard its STDERR:
1352
1353               $output = `cmd 2>/dev/null`;
1354
1355           To capture a command's STDERR but discard its STDOUT (ordering is
1356           important here):
1357
1358               $output = `cmd 2>&1 1>/dev/null`;
1359
1360           To exchange a command's STDOUT and STDERR in order to capture the
1361           STDERR but leave its STDOUT to come out the old STDERR:
1362
1363               $output = `cmd 3>&1 1>&2 2>&3 3>&-`;
1364
1365           To read both a command's STDOUT and its STDERR separately, it's
1366           easiest to redirect them separately to files, and then read from
1367           those files when the program is done:
1368
1369               system("program args 1>program.stdout 2>program.stderr");
1370
1371           The STDIN filehandle used by the command is inherited from Perl's
1372           STDIN.  For example:
1373
1374               open BLAM, "blam" || die "Can't open: $!";
1375               open STDIN, "<&BLAM";
1376               print `sort`;
1377
1378           will print the sorted contents of the file "blam".
1379
1380           Using single-quote as a delimiter protects the command from Perl's
1381           double-quote interpolation, passing it on to the shell instead:
1382
1383               $perl_info  = qx(ps $$);            # that's Perl's $$
1384               $shell_info = qx'ps $$';            # that's the new shell's $$
1385
1386           How that string gets evaluated is entirely subject to the command
1387           interpreter on your system.  On most platforms, you will have to
1388           protect shell metacharacters if you want them treated literally.
1389           This is in practice difficult to do, as it's unclear how to escape
1390           which characters.  See perlsec for a clean and safe example of a
1391           manual fork() and exec() to emulate backticks safely.
1392
1393           On some platforms (notably DOS-like ones), the shell may not be
1394           capable of dealing with multiline commands, so putting newlines in
1395           the string may not get you what you want.  You may be able to
1396           evaluate multiple commands in a single line by separating them with
1397           the command separator character, if your shell supports that (e.g.
1398           ";" on many Unix shells; "&" on the Windows NT "cmd" shell).
1399
1400           Beginning with v5.6.0, Perl will attempt to flush all files opened
1401           for output before starting the child process, but this may not be
1402           supported on some platforms (see perlport).  To be safe, you may
1403           need to set $| ($AUTOFLUSH in English) or call the "autoflush()"
1404           method of "IO::Handle" on any open handles.
1405
1406           Beware that some command shells may place restrictions on the
1407           length of the command line.  You must ensure your strings don't
1408           exceed this limit after any necessary interpolations.  See the
1409           platform-specific release notes for more details about your
1410           particular environment.
1411
1412           Using this operator can lead to programs that are difficult to
1413           port, because the shell commands called vary between systems, and
1414           may in fact not be present at all.  As one example, the "type"
1415           command under the POSIX shell is very different from the "type"
1416           command under DOS.  That doesn't mean you should go out of your way
1417           to avoid backticks when they're the right way to get something
1418           done.  Perl was made to be a glue language, and one of the things
1419           it glues together is commands.  Just understand what you're getting
1420           yourself into.
1421
1422           See "I/O Operators" for more discussion.
1423
1424       qw/STRING/
1425           Evaluates to a list of the words extracted out of STRING, using
1426           embedded whitespace as the word delimiters.  It can be understood
1427           as being roughly equivalent to:
1428
1429               split(' ', q/STRING/);
1430
1431           the differences being that it generates a real list at compile
1432           time, and in scalar context it returns the last element in the
1433           list.  So this expression:
1434
1435               qw(foo bar baz)
1436
1437           is semantically equivalent to the list:
1438
1439               'foo', 'bar', 'baz'
1440
1441           Some frequently seen examples:
1442
1443               use POSIX qw( setlocale localeconv )
1444               @EXPORT = qw( foo bar baz );
1445
1446           A common mistake is to try to separate the words with comma or to
1447           put comments into a multi-line "qw"-string.  For this reason, the
1448           "use warnings" pragma and the -w switch (that is, the $^W variable)
1449           produces warnings if the STRING contains the "," or the "#"
1450           character.
1451
1452       tr/SEARCHLIST/REPLACEMENTLIST/cds
1453       y/SEARCHLIST/REPLACEMENTLIST/cds
1454           Transliterates all occurrences of the characters found in the
1455           search list with the corresponding character in the replacement
1456           list.  It returns the number of characters replaced or deleted.  If
1457           no string is specified via the =~ or !~ operator, the $_ string is
1458           transliterated.  (The string specified with =~ must be a scalar
1459           variable, an array element, a hash element, or an assignment to one
1460           of those, i.e., an lvalue.)
1461
1462           A character range may be specified with a hyphen, so "tr/A-J/0-9/"
1463           does the same replacement as "tr/ACEGIBDFHJ/0246813579/".  For sed
1464           devotees, "y" is provided as a synonym for "tr".  If the SEARCHLIST
1465           is delimited by bracketing quotes, the REPLACEMENTLIST has its own
1466           pair of quotes, which may or may not be bracketing quotes, e.g.,
1467           "tr[A-Z][a-z]" or "tr(+\-*/)/ABCD/".
1468
1469           Note that "tr" does not do regular expression character classes
1470           such as "\d" or "[:lower:]".  The "tr" operator is not equivalent
1471           to the tr(1) utility.  If you want to map strings between
1472           lower/upper cases, see "lc" in perlfunc and "uc" in perlfunc, and
1473           in general consider using the "s" operator if you need regular
1474           expressions.
1475
1476           Note also that the whole range idea is rather unportable between
1477           character sets--and even within character sets they may cause
1478           results you probably didn't expect.  A sound principle is to use
1479           only ranges that begin from and end at either alphabets of equal
1480           case (a-e, A-E), or digits (0-4).  Anything else is unsafe.  If in
1481           doubt, spell out the character sets in full.
1482
1483           Options:
1484
1485               c   Complement the SEARCHLIST.
1486               d   Delete found but unreplaced characters.
1487               s   Squash duplicate replaced characters.
1488
1489           If the "/c" modifier is specified, the SEARCHLIST character set is
1490           complemented.  If the "/d" modifier is specified, any characters
1491           specified by SEARCHLIST not found in REPLACEMENTLIST are deleted.
1492           (Note that this is slightly more flexible than the behavior of some
1493           tr programs, which delete anything they find in the SEARCHLIST,
1494           period.) If the "/s" modifier is specified, sequences of characters
1495           that were transliterated to the same character are squashed down to
1496           a single instance of the character.
1497
1498           If the "/d" modifier is used, the REPLACEMENTLIST is always
1499           interpreted exactly as specified.  Otherwise, if the
1500           REPLACEMENTLIST is shorter than the SEARCHLIST, the final character
1501           is replicated till it is long enough.  If the REPLACEMENTLIST is
1502           empty, the SEARCHLIST is replicated.  This latter is useful for
1503           counting characters in a class or for squashing character sequences
1504           in a class.
1505
1506           Examples:
1507
1508               $ARGV[1] =~ tr/A-Z/a-z/;    # canonicalize to lower case
1509
1510               $cnt = tr/*/*/;             # count the stars in $_
1511
1512               $cnt = $sky =~ tr/*/*/;     # count the stars in $sky
1513
1514               $cnt = tr/0-9//;            # count the digits in $_
1515
1516               tr/a-zA-Z//s;               # bookkeeper -> bokeper
1517
1518               ($HOST = $host) =~ tr/a-z/A-Z/;
1519
1520               tr/a-zA-Z/ /cs;             # change non-alphas to single space
1521
1522               tr [\200-\377]
1523                  [\000-\177];             # delete 8th bit
1524
1525           If multiple transliterations are given for a character, only the
1526           first one is used:
1527
1528               tr/AAA/XYZ/
1529
1530           will transliterate any A to X.
1531
1532           Because the transliteration table is built at compile time, neither
1533           the SEARCHLIST nor the REPLACEMENTLIST are subjected to double
1534           quote interpolation.  That means that if you want to use variables,
1535           you must use an eval():
1536
1537               eval "tr/$oldlist/$newlist/";
1538               die $@ if $@;
1539
1540               eval "tr/$oldlist/$newlist/, 1" or die $@;
1541
1542       <<EOF
1543           A line-oriented form of quoting is based on the shell "here-
1544           document" syntax.  Following a "<<" you specify a string to
1545           terminate the quoted material, and all lines following the current
1546           line down to the terminating string are the value of the item.
1547
1548           The terminating string may be either an identifier (a word), or
1549           some quoted text.  An unquoted identifier works like double quotes.
1550           There may not be a space between the "<<" and the identifier,
1551           unless the identifier is explicitly quoted.  (If you put a space it
1552           will be treated as a null identifier, which is valid, and matches
1553           the first empty line.)  The terminating string must appear by
1554           itself (unquoted and with no surrounding whitespace) on the
1555           terminating line.
1556
1557           If the terminating string is quoted, the type of quotes used
1558           determine the treatment of the text.
1559
1560           Double Quotes
1561               Double quotes indicate that the text will be interpolated using
1562               exactly the same rules as normal double quoted strings.
1563
1564                      print <<EOF;
1565                   The price is $Price.
1566                   EOF
1567
1568                      print << "EOF"; # same as above
1569                   The price is $Price.
1570                   EOF
1571
1572           Single Quotes
1573               Single quotes indicate the text is to be treated literally with
1574               no interpolation of its content. This is similar to single
1575               quoted strings except that backslashes have no special meaning,
1576               with "\\" being treated as two backslashes and not one as they
1577               would in every other quoting construct.
1578
1579               This is the only form of quoting in perl where there is no need
1580               to worry about escaping content, something that code generators
1581               can and do make good use of.
1582
1583           Backticks
1584               The content of the here doc is treated just as it would be if
1585               the string were embedded in backticks. Thus the content is
1586               interpolated as though it were double quoted and then executed
1587               via the shell, with the results of the execution returned.
1588
1589                      print << `EOC`; # execute command and get results
1590                   echo hi there
1591                   EOC
1592
1593           It is possible to stack multiple here-docs in a row:
1594
1595                  print <<"foo", <<"bar"; # you can stack them
1596               I said foo.
1597               foo
1598               I said bar.
1599               bar
1600
1601                  myfunc(<< "THIS", 23, <<'THAT');
1602               Here's a line
1603               or two.
1604               THIS
1605               and here's another.
1606               THAT
1607
1608           Just don't forget that you have to put a semicolon on the end to
1609           finish the statement, as Perl doesn't know you're not going to try
1610           to do this:
1611
1612                  print <<ABC
1613               179231
1614               ABC
1615                  + 20;
1616
1617           If you want to remove the line terminator from your here-docs, use
1618           "chomp()".
1619
1620               chomp($string = <<'END');
1621               This is a string.
1622               END
1623
1624           If you want your here-docs to be indented with the rest of the
1625           code, you'll need to remove leading whitespace from each line
1626           manually:
1627
1628               ($quote = <<'FINIS') =~ s/^\s+//gm;
1629                  The Road goes ever on and on,
1630                  down from the door where it began.
1631               FINIS
1632
1633           If you use a here-doc within a delimited construct, such as in
1634           "s///eg", the quoted material must come on the lines following the
1635           final delimiter.  So instead of
1636
1637               s/this/<<E . 'that'
1638               the other
1639               E
1640                . 'more '/eg;
1641
1642           you have to write
1643
1644               s/this/<<E . 'that'
1645                . 'more '/eg;
1646               the other
1647               E
1648
1649           If the terminating identifier is on the last line of the program,
1650           you must be sure there is a newline after it; otherwise, Perl will
1651           give the warning Can't find string terminator "END" anywhere before
1652           EOF....
1653
1654           Additionally, the quoting rules for the end of string identifier
1655           are not related to Perl's quoting rules -- "q()", "qq()", and the
1656           like are not supported in place of '' and "", and the only
1657           interpolation is for backslashing the quoting character:
1658
1659               print << "abc\"def";
1660               testing...
1661               abc"def
1662
1663           Finally, quoted strings cannot span multiple lines.  The general
1664           rule is that the identifier must be a string literal.  Stick with
1665           that, and you should be safe.
1666
1667   Gory details of parsing quoted constructs
1668       When presented with something that might have several different
1669       interpretations, Perl uses the DWIM (that's "Do What I Mean") principle
1670       to pick the most probable interpretation.  This strategy is so
1671       successful that Perl programmers often do not suspect the ambivalence
1672       of what they write.  But from time to time, Perl's notions differ
1673       substantially from what the author honestly meant.
1674
1675       This section hopes to clarify how Perl handles quoted constructs.
1676       Although the most common reason to learn this is to unravel
1677       labyrinthine regular expressions, because the initial steps of parsing
1678       are the same for all quoting operators, they are all discussed
1679       together.
1680
1681       The most important Perl parsing rule is the first one discussed below:
1682       when processing a quoted construct, Perl first finds the end of that
1683       construct, then interprets its contents.  If you understand this rule,
1684       you may skip the rest of this section on the first reading.  The other
1685       rules are likely to contradict the user's expectations much less
1686       frequently than this first one.
1687
1688       Some passes discussed below are performed concurrently, but because
1689       their results are the same, we consider them individually.  For
1690       different quoting constructs, Perl performs different numbers of
1691       passes, from one to four, but these passes are always performed in the
1692       same order.
1693
1694       Finding the end
1695           The first pass is finding the end of the quoted construct, where
1696           the information about the delimiters is used in parsing.  During
1697           this search, text between the starting and ending delimiters is
1698           copied to a safe location. The text copied gets delimiter-
1699           independent.
1700
1701           If the construct is a here-doc, the ending delimiter is a line that
1702           has a terminating string as the content. Therefore "<<EOF" is
1703           terminated by "EOF" immediately followed by "\n" and starting from
1704           the first column of the terminating line.  When searching for the
1705           terminating line of a here-doc, nothing is skipped. In other words,
1706           lines after the here-doc syntax are compared with the terminating
1707           string line by line.
1708
1709           For the constructs except here-docs, single characters are used as
1710           starting and ending delimiters. If the starting delimiter is an
1711           opening punctuation (that is "(", "[", "{", or "<"), the ending
1712           delimiter is the corresponding closing punctuation (that is ")",
1713           "]", "}", or ">").  If the starting delimiter is an unpaired
1714           character like "/" or a closing punctuation, the ending delimiter
1715           is same as the starting delimiter.  Therefore a "/" terminates a
1716           "qq//" construct, while a "]" terminates "qq[]" and "qq]]"
1717           constructs.
1718
1719           When searching for single-character delimiters, escaped delimiters
1720           and "\\" are skipped. For example, while searching for terminating
1721           "/", combinations of "\\" and "\/" are skipped.  If the delimiters
1722           are bracketing, nested pairs are also skipped.  For example, while
1723           searching for closing "]" paired with the opening "[", combinations
1724           of "\\", "\]", and "\[" are all skipped, and nested "[" and "]" are
1725           skipped as well.  However, when backslashes are used as the
1726           delimiters (like "qq\\" and "tr\\\"), nothing is skipped.  During
1727           the search for the end, backslashes that escape delimiters are
1728           removed (exactly speaking, they are not copied to the safe
1729           location).
1730
1731           For constructs with three-part delimiters ("s///", "y///", and
1732           "tr///"), the search is repeated once more.  If the first delimiter
1733           is not an opening punctuation, three delimiters must be same such
1734           as "s!!!" and "tr)))", in which case the second delimiter
1735           terminates the left part and starts the right part at once.  If the
1736           left part is delimited by bracketing punctuations (that is "()",
1737           "[]", "{}", or "<>"), the right part needs another pair of
1738           delimiters such as "s(){}" and "tr[]//".  In these cases,
1739           whitespaces and comments are allowed between both parts, though the
1740           comment must follow at least one whitespace; otherwise a character
1741           expected as the start of the comment may be regarded as the
1742           starting delimiter of the right part.
1743
1744           During this search no attention is paid to the semantics of the
1745           construct.  Thus:
1746
1747               "$hash{"$foo/$bar"}"
1748
1749           or:
1750
1751               m/
1752                 bar       # NOT a comment, this slash / terminated m//!
1753                /x
1754
1755           do not form legal quoted expressions.   The quoted part ends on the
1756           first """ and "/", and the rest happens to be a syntax error.
1757           Because the slash that terminated "m//" was followed by a "SPACE",
1758           the example above is not "m//x", but rather "m//" with no "/x"
1759           modifier.  So the embedded "#" is interpreted as a literal "#".
1760
1761           Also no attention is paid to "\c\" (multichar control char syntax)
1762           during this search. Thus the second "\" in "qq/\c\/" is interpreted
1763           as a part of "\/", and the following "/" is not recognized as a
1764           delimiter.  Instead, use "\034" or "\x1c" at the end of quoted
1765           constructs.
1766
1767       Interpolation
1768           The next step is interpolation in the text obtained, which is now
1769           delimiter-independent.  There are multiple cases.
1770
1771           "<<'EOF'"
1772               No interpolation is performed.  Note that the combination "\\"
1773               is left intact, since escaped delimiters are not available for
1774               here-docs.
1775
1776           "m''", the pattern of "s'''"
1777               No interpolation is performed at this stage.  Any backslashed
1778               sequences including "\\" are treated at the stage to "parsing
1779               regular expressions".
1780
1781           '', "q//", "tr'''", "y'''", the replacement of "s'''"
1782               The only interpolation is removal of "\" from pairs of "\\".
1783               Therefore "-" in "tr'''" and "y'''" is treated literally as a
1784               hyphen and no character range is available.  "\1" in the
1785               replacement of "s'''" does not work as $1.
1786
1787           "tr///", "y///"
1788               No variable interpolation occurs.  String modifying
1789               combinations for case and quoting such as "\Q", "\U", and "\E"
1790               are not recognized.  The other escape sequences such as "\200"
1791               and "\t" and backslashed characters such as "\\" and "\-" are
1792               converted to appropriate literals.  The character "-" is
1793               treated specially and therefore "\-" is treated as a literal
1794               "-".
1795
1796           "", "``", "qq//", "qx//", "<file*glob>", "<<"EOF""
1797               "\Q", "\U", "\u", "\L", "\l" (possibly paired with "\E") are
1798               converted to corresponding Perl constructs.  Thus,
1799               "$foo\Qbaz$bar" is converted to "$foo . (quotemeta("baz" .
1800               $bar))" internally.  The other escape sequences such as "\200"
1801               and "\t" and backslashed characters such as "\\" and "\-" are
1802               replaced with appropriate expansions.
1803
1804               Let it be stressed that whatever falls between "\Q" and "\E" is
1805               interpolated in the usual way.  Something like "\Q\\E" has no
1806               "\E" inside.  instead, it has "\Q", "\\", and "E", so the
1807               result is the same as for "\\\\E".  As a general rule,
1808               backslashes between "\Q" and "\E" may lead to counterintuitive
1809               results.  So, "\Q\t\E" is converted to "quotemeta("\t")", which
1810               is the same as "\\\t" (since TAB is not alphanumeric).  Note
1811               also that:
1812
1813                 $str = '\t';
1814                 return "\Q$str";
1815
1816               may be closer to the conjectural intention of the writer of
1817               "\Q\t\E".
1818
1819               Interpolated scalars and arrays are converted internally to the
1820               "join" and "." catenation operations.  Thus, "$foo XXX '@arr'"
1821               becomes:
1822
1823                 $foo . " XXX '" . (join $", @arr) . "'";
1824
1825               All operations above are performed simultaneously, left to
1826               right.
1827
1828               Because the result of "\Q STRING \E" has all metacharacters
1829               quoted, there is no way to insert a literal "$" or "@" inside a
1830               "\Q\E" pair.  If protected by "\", "$" will be quoted to became
1831               "\\\$"; if not, it is interpreted as the start of an
1832               interpolated scalar.
1833
1834               Note also that the interpolation code needs to make a decision
1835               on where the interpolated scalar ends.  For instance, whether
1836               "a $b -> {c}" really means:
1837
1838                 "a " . $b . " -> {c}";
1839
1840               or:
1841
1842                 "a " . $b -> {c};
1843
1844               Most of the time, the longest possible text that does not
1845               include spaces between components and which contains matching
1846               braces or brackets.  because the outcome may be determined by
1847               voting based on heuristic estimators, the result is not
1848               strictly predictable.  Fortunately, it's usually correct for
1849               ambiguous cases.
1850
1851           the replacement of "s///"
1852               Processing of "\Q", "\U", "\u", "\L", "\l", and interpolation
1853               happens as with "qq//" constructs.
1854
1855               It is at this step that "\1" is begrudgingly converted to $1 in
1856               the replacement text of "s///", in order to correct the
1857               incorrigible sed hackers who haven't picked up the saner idiom
1858               yet.  A warning is emitted if the "use warnings" pragma or the
1859               -w command-line flag (that is, the $^W variable) was set.
1860
1861           "RE" in "?RE?", "/RE/", "m/RE/", "s/RE/foo/",
1862               Processing of "\Q", "\U", "\u", "\L", "\l", "\E", and
1863               interpolation happens (almost) as with "qq//" constructs.
1864
1865               However any other combinations of "\" followed by a character
1866               are not substituted but only skipped, in order to parse them as
1867               regular expressions at the following step.  As "\c" is skipped
1868               at this step, "@" of "\c@" in RE is possibly treated as an
1869               array symbol (for example @foo), even though the same text in
1870               "qq//" gives interpolation of "\c@".
1871
1872               Moreover, inside "(?{BLOCK})", "(?# comment )", and a
1873               "#"-comment in a "//x"-regular expression, no processing is
1874               performed whatsoever.  This is the first step at which the
1875               presence of the "//x" modifier is relevant.
1876
1877               Interpolation in patterns has several quirks: $|, $(, $), "@+"
1878               and "@-" are not interpolated, and constructs $var[SOMETHING]
1879               are voted (by several different estimators) to be either an
1880               array element or $var followed by an RE alternative.  This is
1881               where the notation "${arr[$bar]}" comes handy: "/${arr[0-9]}/"
1882               is interpreted as array element "-9", not as a regular
1883               expression from the variable $arr followed by a digit, which
1884               would be the interpretation of "/$arr[0-9]/".  Since voting
1885               among different estimators may occur, the result is not
1886               predictable.
1887
1888               The lack of processing of "\\" creates specific restrictions on
1889               the post-processed text.  If the delimiter is "/", one cannot
1890               get the combination "\/" into the result of this step.  "/"
1891               will finish the regular expression, "\/" will be stripped to
1892               "/" on the previous step, and "\\/" will be left as is.
1893               Because "/" is equivalent to "\/" inside a regular expression,
1894               this does not matter unless the delimiter happens to be
1895               character special to the RE engine, such as in "s*foo*bar*",
1896               "m[foo]", or "?foo?"; or an alphanumeric char, as in:
1897
1898                 m m ^ a \s* b mmx;
1899
1900               In the RE above, which is intentionally obfuscated for
1901               illustration, the delimiter is "m", the modifier is "mx", and
1902               after delimiter-removal the RE is the same as for "m/ ^ a \s* b
1903               /mx".  There's more than one reason you're encouraged to
1904               restrict your delimiters to non-alphanumeric, non-whitespace
1905               choices.
1906
1907           This step is the last one for all constructs except regular
1908           expressions, which are processed further.
1909
1910       parsing regular expressions
1911           Previous steps were performed during the compilation of Perl code,
1912           but this one happens at run time--although it may be optimized to
1913           be calculated at compile time if appropriate.  After preprocessing
1914           described above, and possibly after evaluation if concatenation,
1915           joining, casing translation, or metaquoting are involved, the
1916           resulting string is passed to the RE engine for compilation.
1917
1918           Whatever happens in the RE engine might be better discussed in
1919           perlre, but for the sake of continuity, we shall do so here.
1920
1921           This is another step where the presence of the "//x" modifier is
1922           relevant.  The RE engine scans the string from left to right and
1923           converts it to a finite automaton.
1924
1925           Backslashed characters are either replaced with corresponding
1926           literal strings (as with "\{"), or else they generate special nodes
1927           in the finite automaton (as with "\b").  Characters special to the
1928           RE engine (such as "|") generate corresponding nodes or groups of
1929           nodes.  "(?#...)" comments are ignored.  All the rest is either
1930           converted to literal strings to match, or else is ignored (as is
1931           whitespace and "#"-style comments if "//x" is present).
1932
1933           Parsing of the bracketed character class construct, "[...]", is
1934           rather different than the rule used for the rest of the pattern.
1935           The terminator of this construct is found using the same rules as
1936           for finding the terminator of a "{}"-delimited construct, the only
1937           exception being that "]" immediately following "[" is treated as
1938           though preceded by a backslash.  Similarly, the terminator of
1939           "(?{...})" is found using the same rules as for finding the
1940           terminator of a "{}"-delimited construct.
1941
1942           It is possible to inspect both the string given to RE engine and
1943           the resulting finite automaton.  See the arguments
1944           "debug"/"debugcolor" in the "use re" pragma, as well as Perl's -Dr
1945           command-line switch documented in "Command Switches" in perlrun.
1946
1947       Optimization of regular expressions
1948           This step is listed for completeness only.  Since it does not
1949           change semantics, details of this step are not documented and are
1950           subject to change without notice.  This step is performed over the
1951           finite automaton that was generated during the previous pass.
1952
1953           It is at this stage that "split()" silently optimizes "/^/" to mean
1954           "/^/m".
1955
1956   I/O Operators
1957       There are several I/O operators you should know about.
1958
1959       A string enclosed by backticks (grave accents) first undergoes double-
1960       quote interpolation.  It is then interpreted as an external command,
1961       and the output of that command is the value of the backtick string,
1962       like in a shell.  In scalar context, a single string consisting of all
1963       output is returned.  In list context, a list of values is returned, one
1964       per line of output.  (You can set $/ to use a different line
1965       terminator.)  The command is executed each time the pseudo-literal is
1966       evaluated.  The status value of the command is returned in $? (see
1967       perlvar for the interpretation of $?).  Unlike in csh, no translation
1968       is done on the return data--newlines remain newlines.  Unlike in any of
1969       the shells, single quotes do not hide variable names in the command
1970       from interpretation.  To pass a literal dollar-sign through to the
1971       shell you need to hide it with a backslash.  The generalized form of
1972       backticks is "qx//".  (Because backticks always undergo shell expansion
1973       as well, see perlsec for security concerns.)
1974
1975       In scalar context, evaluating a filehandle in angle brackets yields the
1976       next line from that file (the newline, if any, included), or "undef" at
1977       end-of-file or on error.  When $/ is set to "undef" (sometimes known as
1978       file-slurp mode) and the file is empty, it returns '' the first time,
1979       followed by "undef" subsequently.
1980
1981       Ordinarily you must assign the returned value to a variable, but there
1982       is one situation where an automatic assignment happens.  If and only if
1983       the input symbol is the only thing inside the conditional of a "while"
1984       statement (even if disguised as a "for(;;)" loop), the value is
1985       automatically assigned to the global variable $_, destroying whatever
1986       was there previously.  (This may seem like an odd thing to you, but
1987       you'll use the construct in almost every Perl script you write.)  The
1988       $_ variable is not implicitly localized.  You'll have to put a "local
1989       $_;" before the loop if you want that to happen.
1990
1991       The following lines are equivalent:
1992
1993           while (defined($_ = <STDIN>)) { print; }
1994           while ($_ = <STDIN>) { print; }
1995           while (<STDIN>) { print; }
1996           for (;<STDIN>;) { print; }
1997           print while defined($_ = <STDIN>);
1998           print while ($_ = <STDIN>);
1999           print while <STDIN>;
2000
2001       This also behaves similarly, but avoids $_ :
2002
2003           while (my $line = <STDIN>) { print $line }
2004
2005       In these loop constructs, the assigned value (whether assignment is
2006       automatic or explicit) is then tested to see whether it is defined.
2007       The defined test avoids problems where line has a string value that
2008       would be treated as false by Perl, for example a "" or a "0" with no
2009       trailing newline.  If you really mean for such values to terminate the
2010       loop, they should be tested for explicitly:
2011
2012           while (($_ = <STDIN>) ne '0') { ... }
2013           while (<STDIN>) { last unless $_; ... }
2014
2015       In other boolean contexts, "<I<filehandle>>" without an explicit
2016       "defined" test or comparison elicit a warning if the "use warnings"
2017       pragma or the -w command-line switch (the $^W variable) is in effect.
2018
2019       The filehandles STDIN, STDOUT, and STDERR are predefined.  (The
2020       filehandles "stdin", "stdout", and "stderr" will also work except in
2021       packages, where they would be interpreted as local identifiers rather
2022       than global.)  Additional filehandles may be created with the open()
2023       function, amongst others.  See perlopentut and "open" in perlfunc for
2024       details on this.
2025
2026       If a <FILEHANDLE> is used in a context that is looking for a list, a
2027       list comprising all input lines is returned, one line per list element.
2028       It's easy to grow to a rather large data space this way, so use with
2029       care.
2030
2031       <FILEHANDLE> may also be spelled "readline(*FILEHANDLE)".  See
2032       "readline" in perlfunc.
2033
2034       The null filehandle <> is special: it can be used to emulate the
2035       behavior of sed and awk.  Input from <> comes either from standard
2036       input, or from each file listed on the command line.  Here's how it
2037       works: the first time <> is evaluated, the @ARGV array is checked, and
2038       if it is empty, $ARGV[0] is set to "-", which when opened gives you
2039       standard input.  The @ARGV array is then processed as a list of
2040       filenames.  The loop
2041
2042           while (<>) {
2043               ...                     # code for each line
2044           }
2045
2046       is equivalent to the following Perl-like pseudo code:
2047
2048           unshift(@ARGV, '-') unless @ARGV;
2049           while ($ARGV = shift) {
2050               open(ARGV, $ARGV);
2051               while (<ARGV>) {
2052                   ...         # code for each line
2053               }
2054           }
2055
2056       except that it isn't so cumbersome to say, and will actually work.  It
2057       really does shift the @ARGV array and put the current filename into the
2058       $ARGV variable.  It also uses filehandle ARGV internally--<> is just a
2059       synonym for <ARGV>, which is magical.  (The pseudo code above doesn't
2060       work because it treats <ARGV> as non-magical.)
2061
2062       Since the null filehandle uses the two argument form of "open" in
2063       perlfunc it interprets special characters, so if you have a script like
2064       this:
2065
2066           while (<>) {
2067               print;
2068           }
2069
2070       and call it with "perl dangerous.pl 'rm -rfv *|'", it actually opens a
2071       pipe, executes the "rm" command and reads "rm"'s output from that pipe.
2072       If you want all items in @ARGV to be interpreted as file names, you can
2073       use the module "ARGV::readonly" from CPAN.
2074
2075       You can modify @ARGV before the first <> as long as the array ends up
2076       containing the list of filenames you really want.  Line numbers ($.)
2077       continue as though the input were one big happy file.  See the example
2078       in "eof" in perlfunc for how to reset line numbers on each file.
2079
2080       If you want to set @ARGV to your own list of files, go right ahead.
2081       This sets @ARGV to all plain text files if no @ARGV was given:
2082
2083           @ARGV = grep { -f && -T } glob('*') unless @ARGV;
2084
2085       You can even set them to pipe commands.  For example, this
2086       automatically filters compressed arguments through gzip:
2087
2088           @ARGV = map { /\.(gz|Z)$/ ? "gzip -dc < $_ |" : $_ } @ARGV;
2089
2090       If you want to pass switches into your script, you can use one of the
2091       Getopts modules or put a loop on the front like this:
2092
2093           while ($_ = $ARGV[0], /^-/) {
2094               shift;
2095               last if /^--$/;
2096               if (/^-D(.*)/) { $debug = $1 }
2097               if (/^-v/)     { $verbose++  }
2098               # ...           # other switches
2099           }
2100
2101           while (<>) {
2102               # ...           # code for each line
2103           }
2104
2105       The <> symbol will return "undef" for end-of-file only once.  If you
2106       call it again after this, it will assume you are processing another
2107       @ARGV list, and if you haven't set @ARGV, will read input from STDIN.
2108
2109       If what the angle brackets contain is a simple scalar variable (e.g.,
2110       <$foo>), then that variable contains the name of the filehandle to
2111       input from, or its typeglob, or a reference to the same.  For example:
2112
2113           $fh = \*STDIN;
2114           $line = <$fh>;
2115
2116       If what's within the angle brackets is neither a filehandle nor a
2117       simple scalar variable containing a filehandle name, typeglob, or
2118       typeglob reference, it is interpreted as a filename pattern to be
2119       globbed, and either a list of filenames or the next filename in the
2120       list is returned, depending on context.  This distinction is determined
2121       on syntactic grounds alone.  That means "<$x>" is always a readline()
2122       from an indirect handle, but "<$hash{key}>" is always a glob().  That's
2123       because $x is a simple scalar variable, but $hash{key} is not--it's a
2124       hash element.  Even "<$x >" (note the extra space) is treated as
2125       "glob("$x ")", not "readline($x)".
2126
2127       One level of double-quote interpretation is done first, but you can't
2128       say "<$foo>" because that's an indirect filehandle as explained in the
2129       previous paragraph.  (In older versions of Perl, programmers would
2130       insert curly brackets to force interpretation as a filename glob:
2131       "<${foo}>".  These days, it's considered cleaner to call the internal
2132       function directly as "glob($foo)", which is probably the right way to
2133       have done it in the first place.)  For example:
2134
2135           while (<*.c>) {
2136               chmod 0644, $_;
2137           }
2138
2139       is roughly equivalent to:
2140
2141           open(FOO, "echo *.c | tr -s ' \t\r\f' '\\012\\012\\012\\012'|");
2142           while (<FOO>) {
2143               chomp;
2144               chmod 0644, $_;
2145           }
2146
2147       except that the globbing is actually done internally using the standard
2148       "File::Glob" extension.  Of course, the shortest way to do the above
2149       is:
2150
2151           chmod 0644, <*.c>;
2152
2153       A (file)glob evaluates its (embedded) argument only when it is starting
2154       a new list.  All values must be read before it will start over.  In
2155       list context, this isn't important because you automatically get them
2156       all anyway.  However, in scalar context the operator returns the next
2157       value each time it's called, or "undef" when the list has run out.  As
2158       with filehandle reads, an automatic "defined" is generated when the
2159       glob occurs in the test part of a "while", because legal glob returns
2160       (e.g. a file called 0) would otherwise terminate the loop.  Again,
2161       "undef" is returned only once.  So if you're expecting a single value
2162       from a glob, it is much better to say
2163
2164           ($file) = <blurch*>;
2165
2166       than
2167
2168           $file = <blurch*>;
2169
2170       because the latter will alternate between returning a filename and
2171       returning false.
2172
2173       If you're trying to do variable interpolation, it's definitely better
2174       to use the glob() function, because the older notation can cause people
2175       to become confused with the indirect filehandle notation.
2176
2177           @files = glob("$dir/*.[ch]");
2178           @files = glob($files[$i]);
2179
2180   Constant Folding
2181       Like C, Perl does a certain amount of expression evaluation at compile
2182       time whenever it determines that all arguments to an operator are
2183       static and have no side effects.  In particular, string concatenation
2184       happens at compile time between literals that don't do variable
2185       substitution.  Backslash interpolation also happens at compile time.
2186       You can say
2187
2188           'Now is the time for all' . "\n" .
2189               'good men to come to.'
2190
2191       and this all reduces to one string internally.  Likewise, if you say
2192
2193           foreach $file (@filenames) {
2194               if (-s $file > 5 + 100 * 2**16) {  }
2195           }
2196
2197       the compiler will precompute the number which that expression
2198       represents so that the interpreter won't have to.
2199
2200   No-ops
2201       Perl doesn't officially have a no-op operator, but the bare constants 0
2202       and 1 are special-cased to not produce a warning in a void context, so
2203       you can for example safely do
2204
2205           1 while foo();
2206
2207   Bitwise String Operators
2208       Bitstrings of any size may be manipulated by the bitwise operators ("~
2209       | & ^").
2210
2211       If the operands to a binary bitwise op are strings of different sizes,
2212       | and ^ ops act as though the shorter operand had additional zero bits
2213       on the right, while the & op acts as though the longer operand were
2214       truncated to the length of the shorter.  The granularity for such
2215       extension or truncation is one or more bytes.
2216
2217           # ASCII-based examples
2218           print "j p \n" ^ " a h";            # prints "JAPH\n"
2219           print "JA" | "  ph\n";              # prints "japh\n"
2220           print "japh\nJunk" & '_____';       # prints "JAPH\n";
2221           print 'p N$' ^ " E<H\n";            # prints "Perl\n";
2222
2223       If you are intending to manipulate bitstrings, be certain that you're
2224       supplying bitstrings: If an operand is a number, that will imply a
2225       numeric bitwise operation.  You may explicitly show which type of
2226       operation you intend by using "" or "0+", as in the examples below.
2227
2228           $foo =  150  |  105;        # yields 255  (0x96 | 0x69 is 0xFF)
2229           $foo = '150' |  105;        # yields 255
2230           $foo =  150  | '105';       # yields 255
2231           $foo = '150' | '105';       # yields string '155' (under ASCII)
2232
2233           $baz = 0+$foo & 0+$bar;     # both ops explicitly numeric
2234           $biz = "$foo" ^ "$bar";     # both ops explicitly stringy
2235
2236       See "vec" in perlfunc for information on how to manipulate individual
2237       bits in a bit vector.
2238
2239   Integer Arithmetic
2240       By default, Perl assumes that it must do most of its arithmetic in
2241       floating point.  But by saying
2242
2243           use integer;
2244
2245       you may tell the compiler that it's okay to use integer operations (if
2246       it feels like it) from here to the end of the enclosing BLOCK.  An
2247       inner BLOCK may countermand this by saying
2248
2249           no integer;
2250
2251       which lasts until the end of that BLOCK.  Note that this doesn't mean
2252       everything is only an integer, merely that Perl may use integer
2253       operations if it is so inclined.  For example, even under "use
2254       integer", if you take the sqrt(2), you'll still get 1.4142135623731 or
2255       so.
2256
2257       Used on numbers, the bitwise operators ("&", "|", "^", "~", "<<", and
2258       ">>") always produce integral results.  (But see also "Bitwise String
2259       Operators".)  However, "use integer" still has meaning for them.  By
2260       default, their results are interpreted as unsigned integers, but if
2261       "use integer" is in effect, their results are interpreted as signed
2262       integers.  For example, "~0" usually evaluates to a large integral
2263       value.  However, "use integer; ~0" is "-1" on two's-complement
2264       machines.
2265
2266   Floating-point Arithmetic
2267       While "use integer" provides integer-only arithmetic, there is no
2268       analogous mechanism to provide automatic rounding or truncation to a
2269       certain number of decimal places.  For rounding to a certain number of
2270       digits, sprintf() or printf() is usually the easiest route.  See
2271       perlfaq4.
2272
2273       Floating-point numbers are only approximations to what a mathematician
2274       would call real numbers.  There are infinitely more reals than floats,
2275       so some corners must be cut.  For example:
2276
2277           printf "%.20g\n", 123456789123456789;
2278           #        produces 123456789123456784
2279
2280       Testing for exact equality of floating-point equality or inequality is
2281       not a good idea.  Here's a (relatively expensive) work-around to
2282       compare whether two floating-point numbers are equal to a particular
2283       number of decimal places.  See Knuth, volume II, for a more robust
2284       treatment of this topic.
2285
2286           sub fp_equal {
2287               my ($X, $Y, $POINTS) = @_;
2288               my ($tX, $tY);
2289               $tX = sprintf("%.${POINTS}g", $X);
2290               $tY = sprintf("%.${POINTS}g", $Y);
2291               return $tX eq $tY;
2292           }
2293
2294       The POSIX module (part of the standard perl distribution) implements
2295       ceil(), floor(), and other mathematical and trigonometric functions.
2296       The Math::Complex module (part of the standard perl distribution)
2297       defines mathematical functions that work on both the reals and the
2298       imaginary numbers.  Math::Complex not as efficient as POSIX, but POSIX
2299       can't work with complex numbers.
2300
2301       Rounding in financial applications can have serious implications, and
2302       the rounding method used should be specified precisely.  In these
2303       cases, it probably pays not to trust whichever system rounding is being
2304       used by Perl, but to instead implement the rounding function you need
2305       yourself.
2306
2307   Bigger Numbers
2308       The standard Math::BigInt and Math::BigFloat modules provide variable-
2309       precision arithmetic and overloaded operators, although they're
2310       currently pretty slow. At the cost of some space and considerable
2311       speed, they avoid the normal pitfalls associated with limited-precision
2312       representations.
2313
2314           use Math::BigInt;
2315           $x = Math::BigInt->new('123456789123456789');
2316           print $x * $x;
2317
2318           # prints +15241578780673678515622620750190521
2319
2320       There are several modules that let you calculate with (bound only by
2321       memory and cpu-time) unlimited or fixed precision. There are also some
2322       non-standard modules that provide faster implementations via external C
2323       libraries.
2324
2325       Here is a short, but incomplete summary:
2326
2327               Math::Fraction          big, unlimited fractions like 9973 / 12967
2328               Math::String            treat string sequences like numbers
2329               Math::FixedPrecision    calculate with a fixed precision
2330               Math::Currency          for currency calculations
2331               Bit::Vector             manipulate bit vectors fast (uses C)
2332               Math::BigIntFast        Bit::Vector wrapper for big numbers
2333               Math::Pari              provides access to the Pari C library
2334               Math::BigInteger        uses an external C library
2335               Math::Cephes            uses external Cephes C library (no big numbers)
2336               Math::Cephes::Fraction  fractions via the Cephes library
2337               Math::GMP               another one using an external C library
2338
2339       Choose wisely.
2340
2341
2342
2343perl v5.10.1                      2009-08-11                         PERLOP(1)
Impressum