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 maintains
494       its own boolean state, even across calls to a subroutine that contains
495       it. It is false as long as its left operand is false.  Once the left
496       operand is true, the range operator stays true until the right operand
497       is true, AFTER which the range operator becomes false again.  It
498       doesn't become false till the next time the range operator is
499       evaluated.  It can test the right operand and become false on the same
500       evaluation it became true (as in awk), but it still returns true once.
501       If you don't want it to test the right operand until the next
502       evaluation, as in sed, just use three dots ("...") instead of two.  In
503       all other regards, "..." behaves just like ".." 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   Yada Yada Operator
736       The yada yada operator (noted "...") is a placeholder for code. Perl
737       parses it without error, but when you try to execute a yada yada, it
738       throws an exception with the text "Unimplemented":
739
740               sub unimplemented { ... }
741
742               eval { unimplemented() };
743               if( $@ eq 'Unimplemented' ) {
744                 print "I found the yada yada!\n";
745                 }
746
747       You can only use the yada yada to stand in for a complete statement.
748       These examples of the yada yada work:
749
750               { ... }
751
752               sub foo { ... }
753
754               ...;
755
756               eval { ... };
757
758               sub foo {
759                               my( $self ) = shift;
760
761                               ...;
762                               }
763
764               do { my $n; ...; print 'Hurrah!' };
765
766       The yada yada cannot stand in for an expression that is part of a
767       larger statement since the "..." is also the three-dot version of the
768       range operator (see "Range Operators"). These examples of the yada yada
769       are still syntax errors:
770
771               print ...;
772
773               open my($fh), '>', '/dev/passwd' or ...;
774
775               if( $condition && ... ) { print "Hello\n" };
776
777       There are some cases where Perl can't immediately tell the difference
778       between an expression and a statement. For instance, the syntax for a
779       block and an anonymous hash reference constructor look the same unless
780       there's something in the braces that give Perl a hint. The yada yada is
781       a syntax error if Perl doesn't guess that the "{ ... }" is a block. In
782       that case, it doesn't think the "..." is the yada yada because it's
783       expecting an expression instead of a statement:
784
785               my @transformed = map { ... } @input;  # syntax error
786
787       You can use a ";" inside your block to denote that the "{ ... }" is a
788       block and not a hash reference constructor. Now the yada yada works:
789
790               my @transformed = map {; ... } @input; # ; disambiguates
791
792               my @transformed = map { ...; } @input; # ; disambiguates
793
794   List Operators (Rightward)
795       On the right side of a list operator, it has very low precedence, such
796       that it controls all comma-separated expressions found there.  The only
797       operators with lower precedence are the logical operators "and", "or",
798       and "not", which may be used to evaluate calls to list operators
799       without the need for extra parentheses:
800
801           open HANDLE, "filename"
802               or die "Can't open: $!\n";
803
804       See also discussion of list operators in "Terms and List Operators
805       (Leftward)".
806
807   Logical Not
808       Unary "not" returns the logical negation of the expression to its
809       right.  It's the equivalent of "!" except for the very low precedence.
810
811   Logical And
812       Binary "and" returns the logical conjunction of the two surrounding
813       expressions.  It's equivalent to && except for the very low precedence.
814       This means that it short-circuits: i.e., the right expression is
815       evaluated only if the left expression is true.
816
817   Logical or, Defined or, and Exclusive Or
818       Binary "or" returns the logical disjunction of the two surrounding
819       expressions.  It's equivalent to || except for the very low precedence.
820       This makes it useful for control flow
821
822           print FH $data              or die "Can't write to FH: $!";
823
824       This means that it short-circuits: i.e., the right expression is
825       evaluated only if the left expression is false.  Due to its precedence,
826       you should probably avoid using this for assignment, only for control
827       flow.
828
829           $a = $b or $c;              # bug: this is wrong
830           ($a = $b) or $c;            # really means this
831           $a = $b || $c;              # better written this way
832
833       However, when it's a list-context assignment and you're trying to use
834       "||" for control flow, you probably need "or" so that the assignment
835       takes higher precedence.
836
837           @info = stat($file) || die;     # oops, scalar sense of stat!
838           @info = stat($file) or die;     # better, now @info gets its due
839
840       Then again, you could always use parentheses.
841
842       Binary "xor" returns the exclusive-OR of the two surrounding
843       expressions.  It cannot short circuit, of course.
844
845   C Operators Missing From Perl
846       Here is what C has that Perl doesn't:
847
848       unary & Address-of operator.  (But see the "\" operator for taking a
849               reference.)
850
851       unary * Dereference-address operator. (Perl's prefix dereferencing
852               operators are typed: $, @, %, and &.)
853
854       (TYPE)  Type-casting operator.
855
856   Quote and Quote-like Operators
857       While we usually think of quotes as literal values, in Perl they
858       function as operators, providing various kinds of interpolating and
859       pattern matching capabilities.  Perl provides customary quote
860       characters for these behaviors, but also provides a way for you to
861       choose your quote character for any of them.  In the following table, a
862       "{}" represents any pair of delimiters you choose.
863
864           Customary  Generic        Meaning        Interpolates
865               ''       q{}          Literal             no
866               ""      qq{}          Literal             yes
867               ``      qx{}          Command             yes*
868                       qw{}         Word list            no
869               //       m{}       Pattern match          yes*
870                       qr{}          Pattern             yes*
871                        s{}{}      Substitution          yes*
872                       tr{}{}    Transliteration         no (but see below)
873               <<EOF                 here-doc            yes*
874
875               * unless the delimiter is ''.
876
877       Non-bracketing delimiters use the same character fore and aft, but the
878       four sorts of brackets (round, angle, square, curly) will all nest,
879       which means that
880
881               q{foo{bar}baz}
882
883       is the same as
884
885               'foo{bar}baz'
886
887       Note, however, that this does not always work for quoting Perl code:
888
889               $s = q{ if($a eq "}") ... }; # WRONG
890
891       is a syntax error. The "Text::Balanced" module (from CPAN, and starting
892       from Perl 5.8 part of the standard distribution) is able to do this
893       properly.
894
895       There can be whitespace between the operator and the quoting
896       characters, except when "#" is being used as the quoting character.
897       "q#foo#" is parsed as the string "foo", while "q #foo#" is the operator
898       "q" followed by a comment.  Its argument will be taken from the next
899       line.  This allows you to write:
900
901           s {foo}  # Replace foo
902             {bar}  # with bar.
903
904       The following escape sequences are available in constructs that
905       interpolate and in transliterations.
906
907           \t          tab             (HT, TAB)
908           \n          newline         (NL)
909           \r          return          (CR)
910           \f          form feed       (FF)
911           \b          backspace       (BS)
912           \a          alarm (bell)    (BEL)
913           \e          escape          (ESC)
914           \033        octal char      (example: ESC)
915           \x1b        hex char        (example: ESC)
916           \x{263a}    wide hex char   (example: SMILEY)
917           \c[         control char    (example: ESC)
918           \N{name}    named Unicode character
919           \N{U+263D}  Unicode character (example: FIRST QUARTER MOON)
920
921       The character following "\c" is mapped to some other character by
922       converting letters to upper case and then (on ASCII systems) by
923       inverting the 7th bit (0x40). The most interesting range is from '@' to
924       '_' (0x40 through 0x5F), resulting in a control character from 0x00
925       through 0x1F. A '?' maps to the DEL character. On EBCDIC systems only
926       '@', the letters, '[', '\', ']', '^', '_' and '?' will work, resulting
927       in 0x00 through 0x1F and 0x7F.
928
929       "\N{U+wide hex char}" means the Unicode character whose Unicode ordinal
930       number is wide hex char.  For documentation of "\N{name}", see
931       charnames.
932
933       NOTE: Unlike C and other languages, Perl has no "\v" escape sequence
934       for the vertical tab (VT - ASCII 11), but you may use "\ck" or "\x0b".
935       ("\v" does have meaning in regular expression patterns in Perl, see
936       perlre.)
937
938       The following escape sequences are available in constructs that
939       interpolate, but not in transliterations.
940
941           \l          lowercase next char
942           \u          uppercase next char
943           \L          lowercase till \E
944           \U          uppercase till \E
945           \E          end case modification
946           \Q          quote non-word characters till \E
947
948       If "use locale" is in effect, the case map used by "\l", "\L", "\u" and
949       "\U" is taken from the current locale.  See perllocale.  If Unicode
950       (for example, "\N{}" or wide hex characters of 0x100 or beyond) is
951       being used, the case map used by "\l", "\L", "\u" and "\U" is as
952       defined by Unicode.
953
954       All systems use the virtual "\n" to represent a line terminator, called
955       a "newline".  There is no such thing as an unvarying, physical newline
956       character.  It is only an illusion that the operating system, device
957       drivers, C libraries, and Perl all conspire to preserve.  Not all
958       systems read "\r" as ASCII CR and "\n" as ASCII LF.  For example, on a
959       Mac, these are reversed, and on systems without line terminator,
960       printing "\n" may emit no actual data.  In general, use "\n" when you
961       mean a "newline" for your system, but use the literal ASCII when you
962       need an exact character.  For example, most networking protocols expect
963       and prefer a CR+LF ("\015\012" or "\cM\cJ") for line terminators, and
964       although they often accept just "\012", they seldom tolerate just
965       "\015".  If you get in the habit of using "\n" for networking, you may
966       be burned some day.
967
968       For constructs that do interpolate, variables beginning with ""$"" or
969       ""@"" are interpolated.  Subscripted variables such as $a[3] or
970       "$href->{key}[0]" are also interpolated, as are array and hash slices.
971       But method calls such as "$obj->meth" are not.
972
973       Interpolating an array or slice interpolates the elements in order,
974       separated by the value of $", so is equivalent to interpolating "join
975       $", @array".    "Punctuation" arrays such as "@*" are only interpolated
976       if the name is enclosed in braces "@{*}", but special arrays @_, "@+",
977       and "@-" are interpolated, even without braces.
978
979       You cannot include a literal "$" or "@" within a "\Q" sequence.  An
980       unescaped "$" or "@" interpolates the corresponding variable, while
981       escaping will cause the literal string "\$" to be inserted.  You'll
982       need to write something like "m/\Quser\E\@\Qhost/".
983
984       Patterns are subject to an additional level of interpretation as a
985       regular expression.  This is done as a second pass, after variables are
986       interpolated, so that regular expressions may be incorporated into the
987       pattern from the variables.  If this is not what you want, use "\Q" to
988       interpolate a variable literally.
989
990       Apart from the behavior described above, Perl does not expand multiple
991       levels of interpolation.  In particular, contrary to the expectations
992       of shell programmers, back-quotes do NOT interpolate within double
993       quotes, nor do single quotes impede evaluation of variables when used
994       within double quotes.
995
996   Regexp Quote-Like Operators
997       Here are the quote-like operators that apply to pattern matching and
998       related activities.
999
1000       qr/STRING/msixpo
1001               This operator quotes (and possibly compiles) its STRING as a
1002               regular expression.  STRING is interpolated the same way as
1003               PATTERN in "m/PATTERN/".  If "'" is used as the delimiter, no
1004               interpolation is done.  Returns a Perl value which may be used
1005               instead of the corresponding "/STRING/msixpo" expression. The
1006               returned value is a normalized version of the original pattern.
1007               It magically differs from a string containing the same
1008               characters: "ref(qr/x/)" returns "Regexp", even though
1009               dereferencing the result returns undef.
1010
1011               For example,
1012
1013                   $rex = qr/my.STRING/is;
1014                   print $rex;                 # prints (?si-xm:my.STRING)
1015                   s/$rex/foo/;
1016
1017               is equivalent to
1018
1019                   s/my.STRING/foo/is;
1020
1021               The result may be used as a subpattern in a match:
1022
1023                   $re = qr/$pattern/;
1024                   $string =~ /foo${re}bar/;   # can be interpolated in other patterns
1025                   $string =~ $re;             # or used standalone
1026                   $string =~ /$re/;           # or this way
1027
1028               Since Perl may compile the pattern at the moment of execution
1029               of qr() operator, using qr() may have speed advantages in some
1030               situations, notably if the result of qr() is used standalone:
1031
1032                   sub match {
1033                       my $patterns = shift;
1034                       my @compiled = map qr/$_/i, @$patterns;
1035                       grep {
1036                           my $success = 0;
1037                           foreach my $pat (@compiled) {
1038                               $success = 1, last if /$pat/;
1039                           }
1040                           $success;
1041                       } @_;
1042                   }
1043
1044               Precompilation of the pattern into an internal representation
1045               at the moment of qr() avoids a need to recompile the pattern
1046               every time a match "/$pat/" is attempted.  (Perl has many other
1047               internal optimizations, but none would be triggered in the
1048               above example if we did not use qr() operator.)
1049
1050               Options are:
1051
1052                   m   Treat string as multiple lines.
1053                   s   Treat string as single line. (Make . match a newline)
1054                   i   Do case-insensitive pattern matching.
1055                   x   Use extended regular expressions.
1056                   p   When matching preserve a copy of the matched string so
1057                       that ${^PREMATCH}, ${^MATCH}, ${^POSTMATCH} will be defined.
1058                   o   Compile pattern only once.
1059
1060               If a precompiled pattern is embedded in a larger pattern then
1061               the effect of 'msixp' will be propagated appropriately.  The
1062               effect of the 'o' modifier has is not propagated, being
1063               restricted to those patterns explicitly using it.
1064
1065               See perlre for additional information on valid syntax for
1066               STRING, and for a detailed look at the semantics of regular
1067               expressions.
1068
1069       m/PATTERN/msixpogc
1070       /PATTERN/msixpogc
1071               Searches a string for a pattern match, and in scalar context
1072               returns true if it succeeds, false if it fails.  If no string
1073               is specified via the "=~" or "!~" operator, the $_ string is
1074               searched.  (The string specified with "=~" need not be an
1075               lvalue--it may be the result of an expression evaluation, but
1076               remember the "=~" binds rather tightly.)  See also perlre.  See
1077               perllocale for discussion of additional considerations that
1078               apply when "use locale" is in effect.
1079
1080               Options are as described in "qr//"; in addition, the following
1081               match process modifiers are available:
1082
1083                   g   Match globally, i.e., find all occurrences.
1084                   c   Do not reset search position on a failed match when /g is in effect.
1085
1086               If "/" is the delimiter then the initial "m" is optional.  With
1087               the "m" you can use any pair of non-whitespace characters as
1088               delimiters.  This is particularly useful for matching path
1089               names that contain "/", to avoid LTS (leaning toothpick
1090               syndrome).  If "?" is the delimiter, then the match-only-once
1091               rule of "?PATTERN?" applies.  If "'" is the delimiter, no
1092               interpolation is performed on the PATTERN.  When using a
1093               character valid in an identifier, whitespace is required after
1094               the "m".
1095
1096               PATTERN may contain variables, which will be interpolated (and
1097               the pattern recompiled) every time the pattern search is
1098               evaluated, except for when the delimiter is a single quote.
1099               (Note that $(, $), and $| are not interpolated because they
1100               look like end-of-string tests.)  If you want such a pattern to
1101               be compiled only once, add a "/o" after the trailing delimiter.
1102               This avoids expensive run-time recompilations, and is useful
1103               when the value you are interpolating won't change over the life
1104               of the script.  However, mentioning "/o" constitutes a promise
1105               that you won't change the variables in the pattern.  If you
1106               change them, Perl won't even notice.  See also "STRING/msixpo""
1107               in "qr.
1108
1109       The empty pattern //
1110               If the PATTERN evaluates to the empty string, the last
1111               successfully matched regular expression is used instead. In
1112               this case, only the "g" and "c" flags on the empty pattern is
1113               honoured - the other flags are taken from the original pattern.
1114               If no match has previously succeeded, this will (silently) act
1115               instead as a genuine empty pattern (which will always match).
1116
1117               Note that it's possible to confuse Perl into thinking "//" (the
1118               empty regex) is really "//" (the defined-or operator).  Perl is
1119               usually pretty good about this, but some pathological cases
1120               might trigger this, such as "$a///" (is that "($a) / (//)" or
1121               "$a // /"?) and "print $fh //" ("print $fh(//" or "print($fh
1122               //"?).  In all of these examples, Perl will assume you meant
1123               defined-or.  If you meant the empty regex, just use parentheses
1124               or spaces to disambiguate, or even prefix the empty regex with
1125               an "m" (so "//" becomes "m//").
1126
1127       Matching in list context
1128               If the "/g" option is not used, "m//" in list context returns a
1129               list consisting of the subexpressions matched by the
1130               parentheses in the pattern, i.e., ($1, $2, $3...).  (Note that
1131               here $1 etc. are also set, and that this differs from Perl 4's
1132               behavior.)  When there are no parentheses in the pattern, the
1133               return value is the list "(1)" for success.  With or without
1134               parentheses, an empty list is returned upon failure.
1135
1136               Examples:
1137
1138                   open(TTY, '/dev/tty');
1139                   <TTY> =~ /^y/i && foo();    # do foo if desired
1140
1141                   if (/Version: *([0-9.]*)/) { $version = $1; }
1142
1143                   next if m#^/usr/spool/uucp#;
1144
1145                   # poor man's grep
1146                   $arg = shift;
1147                   while (<>) {
1148                       print if /$arg/o;       # compile only once
1149                   }
1150
1151                   if (($F1, $F2, $Etc) = ($foo =~ /^(\S+)\s+(\S+)\s*(.*)/))
1152
1153               This last example splits $foo into the first two words and the
1154               remainder of the line, and assigns those three fields to $F1,
1155               $F2, and $Etc.  The conditional is true if any variables were
1156               assigned, i.e., if the pattern matched.
1157
1158               The "/g" modifier specifies global pattern matching--that is,
1159               matching as many times as possible within the string.  How it
1160               behaves depends on the context.  In list context, it returns a
1161               list of the substrings matched by any capturing parentheses in
1162               the regular expression.  If there are no parentheses, it
1163               returns a list of all the matched strings, as if there were
1164               parentheses around the whole pattern.
1165
1166               In scalar context, each execution of "m//g" finds the next
1167               match, returning true if it matches, and false if there is no
1168               further match.  The position after the last match can be read
1169               or set using the pos() function; see "pos" in perlfunc.   A
1170               failed match normally resets the search position to the
1171               beginning of the string, but you can avoid that by adding the
1172               "/c" modifier (e.g. "m//gc").  Modifying the target string also
1173               resets the search position.
1174
1175       \G assertion
1176               You can intermix "m//g" matches with "m/\G.../g", where "\G" is
1177               a zero-width assertion that matches the exact position where
1178               the previous "m//g", if any, left off.  Without the "/g"
1179               modifier, the "\G" assertion still anchors at pos(), but the
1180               match is of course only attempted once.  Using "\G" without
1181               "/g" on a target string that has not previously had a "/g"
1182               match applied to it is the same as using the "\A" assertion to
1183               match the beginning of the string.  Note also that, currently,
1184               "\G" is only properly supported when anchored at the very
1185               beginning of the pattern.
1186
1187               Examples:
1188
1189                   # list context
1190                   ($one,$five,$fifteen) = (`uptime` =~ /(\d+\.\d+)/g);
1191
1192                   # scalar context
1193                   $/ = "";
1194                   while (defined($paragraph = <>)) {
1195                       while ($paragraph =~ /[a-z]['")]*[.!?]+['")]*\s/g) {
1196                           $sentences++;
1197                       }
1198                   }
1199                   print "$sentences\n";
1200
1201                   # using m//gc with \G
1202                   $_ = "ppooqppqq";
1203                   while ($i++ < 2) {
1204                       print "1: '";
1205                       print $1 while /(o)/gc; print "', pos=", pos, "\n";
1206                       print "2: '";
1207                       print $1 if /\G(q)/gc;  print "', pos=", pos, "\n";
1208                       print "3: '";
1209                       print $1 while /(p)/gc; print "', pos=", pos, "\n";
1210                   }
1211                   print "Final: '$1', pos=",pos,"\n" if /\G(.)/;
1212
1213               The last example should print:
1214
1215                   1: 'oo', pos=4
1216                   2: 'q', pos=5
1217                   3: 'pp', pos=7
1218                   1: '', pos=7
1219                   2: 'q', pos=8
1220                   3: '', pos=8
1221                   Final: 'q', pos=8
1222
1223               Notice that the final match matched "q" instead of "p", which a
1224               match without the "\G" anchor would have done. Also note that
1225               the final match did not update "pos". "pos" is only updated on
1226               a "/g" match. If the final match did indeed match "p", it's a
1227               good bet that you're running an older (pre-5.6.0) Perl.
1228
1229               A useful idiom for "lex"-like scanners is "/\G.../gc".  You can
1230               combine several regexps like this to process a string part-by-
1231               part, doing different actions depending on which regexp
1232               matched.  Each regexp tries to match where the previous one
1233               leaves off.
1234
1235                $_ = <<'EOL';
1236                     $url = URI::URL->new( "http://example.com/" ); die if $url eq "xXx";
1237                EOL
1238                LOOP:
1239                   {
1240                     print(" digits"),         redo LOOP if /\G\d+\b[,.;]?\s*/gc;
1241                     print(" lowercase"),      redo LOOP if /\G[a-z]+\b[,.;]?\s*/gc;
1242                     print(" UPPERCASE"),      redo LOOP if /\G[A-Z]+\b[,.;]?\s*/gc;
1243                     print(" Capitalized"),    redo LOOP if /\G[A-Z][a-z]+\b[,.;]?\s*/gc;
1244                     print(" MiXeD"),          redo LOOP if /\G[A-Za-z]+\b[,.;]?\s*/gc;
1245                     print(" alphanumeric"),   redo LOOP if /\G[A-Za-z0-9]+\b[,.;]?\s*/gc;
1246                     print(" line-noise"),     redo LOOP if /\G[^A-Za-z0-9]+/gc;
1247                     print ". That's all!\n";
1248                   }
1249
1250               Here is the output (split into several lines):
1251
1252                line-noise lowercase line-noise lowercase UPPERCASE line-noise
1253                UPPERCASE line-noise lowercase line-noise lowercase line-noise
1254                lowercase lowercase line-noise lowercase lowercase line-noise
1255                MiXeD line-noise. That's all!
1256
1257       ?PATTERN?
1258               This is just like the "/pattern/" search, except that it
1259               matches only once between calls to the reset() operator.  This
1260               is a useful optimization when you want to see only the first
1261               occurrence of something in each file of a set of files, for
1262               instance.  Only "??"  patterns local to the current package are
1263               reset.
1264
1265                   while (<>) {
1266                       if (?^$?) {
1267                                           # blank line between header and body
1268                       }
1269                   } continue {
1270                       reset if eof;       # clear ?? status for next file
1271                   }
1272
1273               This usage is vaguely deprecated, which means it just might
1274               possibly be removed in some distant future version of Perl,
1275               perhaps somewhere around the year 2168.
1276
1277       s/PATTERN/REPLACEMENT/msixpogce
1278               Searches a string for a pattern, and if found, replaces that
1279               pattern with the replacement text and returns the number of
1280               substitutions made.  Otherwise it returns false (specifically,
1281               the empty string).
1282
1283               If no string is specified via the "=~" or "!~" operator, the $_
1284               variable is searched and modified.  (The string specified with
1285               "=~" must be scalar variable, an array element, a hash element,
1286               or an assignment to one of those, i.e., an lvalue.)
1287
1288               If the delimiter chosen is a single quote, no interpolation is
1289               done on either the PATTERN or the REPLACEMENT.  Otherwise, if
1290               the PATTERN contains a $ that looks like a variable rather than
1291               an end-of-string test, the variable will be interpolated into
1292               the pattern at run-time.  If you want the pattern compiled only
1293               once the first time the variable is interpolated, use the "/o"
1294               option.  If the pattern evaluates to the empty string, the last
1295               successfully executed regular expression is used instead.  See
1296               perlre for further explanation on these.  See perllocale for
1297               discussion of additional considerations that apply when "use
1298               locale" is in effect.
1299
1300               Options are as with m// with the addition of the following
1301               replacement specific options:
1302
1303                   e   Evaluate the right side as an expression.
1304                   ee  Evaluate the right side as a string then eval the result
1305
1306               Any non-whitespace delimiter may replace the slashes.  Add
1307               space after the "s" when using a character allowed in
1308               identifiers.  If single quotes are used, no interpretation is
1309               done on the replacement string (the "/e" modifier overrides
1310               this, however).  Unlike Perl 4, Perl 5 treats backticks as
1311               normal delimiters; the replacement text is not evaluated as a
1312               command.  If the PATTERN is delimited by bracketing quotes, the
1313               REPLACEMENT has its own pair of quotes, which may or may not be
1314               bracketing quotes, e.g., "s(foo)(bar)" or "s<foo>/bar/".  A
1315               "/e" will cause the replacement portion to be treated as a
1316               full-fledged Perl expression and evaluated right then and
1317               there.  It is, however, syntax checked at compile-time. A
1318               second "e" modifier will cause the replacement portion to be
1319               "eval"ed before being run as a Perl expression.
1320
1321               Examples:
1322
1323                   s/\bgreen\b/mauve/g;                # don't change wintergreen
1324
1325                   $path =~ s|/usr/bin|/usr/local/bin|;
1326
1327                   s/Login: $foo/Login: $bar/; # run-time pattern
1328
1329                   ($foo = $bar) =~ s/this/that/;      # copy first, then change
1330
1331                   $count = ($paragraph =~ s/Mister\b/Mr./g);  # get change-count
1332
1333                   $_ = 'abc123xyz';
1334                   s/\d+/$&*2/e;               # yields 'abc246xyz'
1335                   s/\d+/sprintf("%5d",$&)/e;  # yields 'abc  246xyz'
1336                   s/\w/$& x 2/eg;             # yields 'aabbcc  224466xxyyzz'
1337
1338                   s/%(.)/$percent{$1}/g;      # change percent escapes; no /e
1339                   s/%(.)/$percent{$1} || $&/ge;       # expr now, so /e
1340                   s/^=(\w+)/pod($1)/ge;       # use function call
1341
1342                   # expand variables in $_, but dynamics only, using
1343                   # symbolic dereferencing
1344                   s/\$(\w+)/${$1}/g;
1345
1346                   # Add one to the value of any numbers in the string
1347                   s/(\d+)/1 + $1/eg;
1348
1349                   # This will expand any embedded scalar variable
1350                   # (including lexicals) in $_ : First $1 is interpolated
1351                   # to the variable name, and then evaluated
1352                   s/(\$\w+)/$1/eeg;
1353
1354                   # Delete (most) C comments.
1355                   $program =~ s {
1356                       /\*     # Match the opening delimiter.
1357                       .*?     # Match a minimal number of characters.
1358                       \*/     # Match the closing delimiter.
1359                   } []gsx;
1360
1361                   s/^\s*(.*?)\s*$/$1/;        # trim whitespace in $_, expensively
1362
1363                   for ($variable) {           # trim whitespace in $variable, cheap
1364                       s/^\s+//;
1365                       s/\s+$//;
1366                   }
1367
1368                   s/([^ ]*) *([^ ]*)/$2 $1/;  # reverse 1st two fields
1369
1370               Note the use of $ instead of \ in the last example.  Unlike
1371               sed, we use the \<digit> form in only the left hand side.
1372               Anywhere else it's $<digit>.
1373
1374               Occasionally, you can't use just a "/g" to get all the changes
1375               to occur that you might want.  Here are two common cases:
1376
1377                   # put commas in the right places in an integer
1378                   1 while s/(\d)(\d\d\d)(?!\d)/$1,$2/g;
1379
1380                   # expand tabs to 8-column spacing
1381                   1 while s/\t+/' ' x (length($&)*8 - length($`)%8)/e;
1382
1383   Quote-Like Operators
1384       q/STRING/
1385       'STRING'
1386           A single-quoted, literal string.  A backslash represents a
1387           backslash unless followed by the delimiter or another backslash, in
1388           which case the delimiter or backslash is interpolated.
1389
1390               $foo = q!I said, "You said, 'She said it.'"!;
1391               $bar = q('This is it.');
1392               $baz = '\n';                # a two-character string
1393
1394       qq/STRING/
1395       "STRING"
1396           A double-quoted, interpolated string.
1397
1398               $_ .= qq
1399                (*** The previous line contains the naughty word "$1".\n)
1400                           if /\b(tcl|java|python)\b/i;      # :-)
1401               $baz = "\n";                # a one-character string
1402
1403       qx/STRING/
1404       `STRING`
1405           A string which is (possibly) interpolated and then executed as a
1406           system command with "/bin/sh" or its equivalent.  Shell wildcards,
1407           pipes, and redirections will be honored.  The collected standard
1408           output of the command is returned; standard error is unaffected.
1409           In scalar context, it comes back as a single (potentially multi-
1410           line) string, or undef if the command failed.  In list context,
1411           returns a list of lines (however you've defined lines with $/ or
1412           $INPUT_RECORD_SEPARATOR), or an empty list if the command failed.
1413
1414           Because backticks do not affect standard error, use shell file
1415           descriptor syntax (assuming the shell supports this) if you care to
1416           address this.  To capture a command's STDERR and STDOUT together:
1417
1418               $output = `cmd 2>&1`;
1419
1420           To capture a command's STDOUT but discard its STDERR:
1421
1422               $output = `cmd 2>/dev/null`;
1423
1424           To capture a command's STDERR but discard its STDOUT (ordering is
1425           important here):
1426
1427               $output = `cmd 2>&1 1>/dev/null`;
1428
1429           To exchange a command's STDOUT and STDERR in order to capture the
1430           STDERR but leave its STDOUT to come out the old STDERR:
1431
1432               $output = `cmd 3>&1 1>&2 2>&3 3>&-`;
1433
1434           To read both a command's STDOUT and its STDERR separately, it's
1435           easiest to redirect them separately to files, and then read from
1436           those files when the program is done:
1437
1438               system("program args 1>program.stdout 2>program.stderr");
1439
1440           The STDIN filehandle used by the command is inherited from Perl's
1441           STDIN.  For example:
1442
1443               open BLAM, "blam" || die "Can't open: $!";
1444               open STDIN, "<&BLAM";
1445               print `sort`;
1446
1447           will print the sorted contents of the file "blam".
1448
1449           Using single-quote as a delimiter protects the command from Perl's
1450           double-quote interpolation, passing it on to the shell instead:
1451
1452               $perl_info  = qx(ps $$);            # that's Perl's $$
1453               $shell_info = qx'ps $$';            # that's the new shell's $$
1454
1455           How that string gets evaluated is entirely subject to the command
1456           interpreter on your system.  On most platforms, you will have to
1457           protect shell metacharacters if you want them treated literally.
1458           This is in practice difficult to do, as it's unclear how to escape
1459           which characters.  See perlsec for a clean and safe example of a
1460           manual fork() and exec() to emulate backticks safely.
1461
1462           On some platforms (notably DOS-like ones), the shell may not be
1463           capable of dealing with multiline commands, so putting newlines in
1464           the string may not get you what you want.  You may be able to
1465           evaluate multiple commands in a single line by separating them with
1466           the command separator character, if your shell supports that (e.g.
1467           ";" on many Unix shells; "&" on the Windows NT "cmd" shell).
1468
1469           Beginning with v5.6.0, Perl will attempt to flush all files opened
1470           for output before starting the child process, but this may not be
1471           supported on some platforms (see perlport).  To be safe, you may
1472           need to set $| ($AUTOFLUSH in English) or call the "autoflush()"
1473           method of "IO::Handle" on any open handles.
1474
1475           Beware that some command shells may place restrictions on the
1476           length of the command line.  You must ensure your strings don't
1477           exceed this limit after any necessary interpolations.  See the
1478           platform-specific release notes for more details about your
1479           particular environment.
1480
1481           Using this operator can lead to programs that are difficult to
1482           port, because the shell commands called vary between systems, and
1483           may in fact not be present at all.  As one example, the "type"
1484           command under the POSIX shell is very different from the "type"
1485           command under DOS.  That doesn't mean you should go out of your way
1486           to avoid backticks when they're the right way to get something
1487           done.  Perl was made to be a glue language, and one of the things
1488           it glues together is commands.  Just understand what you're getting
1489           yourself into.
1490
1491           See "I/O Operators" for more discussion.
1492
1493       qw/STRING/
1494           Evaluates to a list of the words extracted out of STRING, using
1495           embedded whitespace as the word delimiters.  It can be understood
1496           as being roughly equivalent to:
1497
1498               split(' ', q/STRING/);
1499
1500           the differences being that it generates a real list at compile
1501           time, and in scalar context it returns the last element in the
1502           list.  So this expression:
1503
1504               qw(foo bar baz)
1505
1506           is semantically equivalent to the list:
1507
1508               'foo', 'bar', 'baz'
1509
1510           Some frequently seen examples:
1511
1512               use POSIX qw( setlocale localeconv )
1513               @EXPORT = qw( foo bar baz );
1514
1515           A common mistake is to try to separate the words with comma or to
1516           put comments into a multi-line "qw"-string.  For this reason, the
1517           "use warnings" pragma and the -w switch (that is, the $^W variable)
1518           produces warnings if the STRING contains the "," or the "#"
1519           character.
1520
1521       tr/SEARCHLIST/REPLACEMENTLIST/cds
1522       y/SEARCHLIST/REPLACEMENTLIST/cds
1523           Transliterates all occurrences of the characters found in the
1524           search list with the corresponding character in the replacement
1525           list.  It returns the number of characters replaced or deleted.  If
1526           no string is specified via the =~ or !~ operator, the $_ string is
1527           transliterated.  (The string specified with =~ must be a scalar
1528           variable, an array element, a hash element, or an assignment to one
1529           of those, i.e., an lvalue.)
1530
1531           A character range may be specified with a hyphen, so "tr/A-J/0-9/"
1532           does the same replacement as "tr/ACEGIBDFHJ/0246813579/".  For sed
1533           devotees, "y" is provided as a synonym for "tr".  If the SEARCHLIST
1534           is delimited by bracketing quotes, the REPLACEMENTLIST has its own
1535           pair of quotes, which may or may not be bracketing quotes, e.g.,
1536           "tr[A-Z][a-z]" or "tr(+\-*/)/ABCD/".
1537
1538           Note that "tr" does not do regular expression character classes
1539           such as "\d" or "[:lower:]".  The "tr" operator is not equivalent
1540           to the tr(1) utility.  If you want to map strings between
1541           lower/upper cases, see "lc" in perlfunc and "uc" in perlfunc, and
1542           in general consider using the "s" operator if you need regular
1543           expressions.
1544
1545           Note also that the whole range idea is rather unportable between
1546           character sets--and even within character sets they may cause
1547           results you probably didn't expect.  A sound principle is to use
1548           only ranges that begin from and end at either alphabets of equal
1549           case (a-e, A-E), or digits (0-4).  Anything else is unsafe.  If in
1550           doubt, spell out the character sets in full.
1551
1552           Options:
1553
1554               c   Complement the SEARCHLIST.
1555               d   Delete found but unreplaced characters.
1556               s   Squash duplicate replaced characters.
1557
1558           If the "/c" modifier is specified, the SEARCHLIST character set is
1559           complemented.  If the "/d" modifier is specified, any characters
1560           specified by SEARCHLIST not found in REPLACEMENTLIST are deleted.
1561           (Note that this is slightly more flexible than the behavior of some
1562           tr programs, which delete anything they find in the SEARCHLIST,
1563           period.) If the "/s" modifier is specified, sequences of characters
1564           that were transliterated to the same character are squashed down to
1565           a single instance of the character.
1566
1567           If the "/d" modifier is used, the REPLACEMENTLIST is always
1568           interpreted exactly as specified.  Otherwise, if the
1569           REPLACEMENTLIST is shorter than the SEARCHLIST, the final character
1570           is replicated till it is long enough.  If the REPLACEMENTLIST is
1571           empty, the SEARCHLIST is replicated.  This latter is useful for
1572           counting characters in a class or for squashing character sequences
1573           in a class.
1574
1575           Examples:
1576
1577               $ARGV[1] =~ tr/A-Z/a-z/;    # canonicalize to lower case
1578
1579               $cnt = tr/*/*/;             # count the stars in $_
1580
1581               $cnt = $sky =~ tr/*/*/;     # count the stars in $sky
1582
1583               $cnt = tr/0-9//;            # count the digits in $_
1584
1585               tr/a-zA-Z//s;               # bookkeeper -> bokeper
1586
1587               ($HOST = $host) =~ tr/a-z/A-Z/;
1588
1589               tr/a-zA-Z/ /cs;             # change non-alphas to single space
1590
1591               tr [\200-\377]
1592                  [\000-\177];             # delete 8th bit
1593
1594           If multiple transliterations are given for a character, only the
1595           first one is used:
1596
1597               tr/AAA/XYZ/
1598
1599           will transliterate any A to X.
1600
1601           Because the transliteration table is built at compile time, neither
1602           the SEARCHLIST nor the REPLACEMENTLIST are subjected to double
1603           quote interpolation.  That means that if you want to use variables,
1604           you must use an eval():
1605
1606               eval "tr/$oldlist/$newlist/";
1607               die $@ if $@;
1608
1609               eval "tr/$oldlist/$newlist/, 1" or die $@;
1610
1611       <<EOF
1612           A line-oriented form of quoting is based on the shell "here-
1613           document" syntax.  Following a "<<" you specify a string to
1614           terminate the quoted material, and all lines following the current
1615           line down to the terminating string are the value of the item.
1616
1617           The terminating string may be either an identifier (a word), or
1618           some quoted text.  An unquoted identifier works like double quotes.
1619           There may not be a space between the "<<" and the identifier,
1620           unless the identifier is explicitly quoted.  (If you put a space it
1621           will be treated as a null identifier, which is valid, and matches
1622           the first empty line.)  The terminating string must appear by
1623           itself (unquoted and with no surrounding whitespace) on the
1624           terminating line.
1625
1626           If the terminating string is quoted, the type of quotes used
1627           determine the treatment of the text.
1628
1629           Double Quotes
1630               Double quotes indicate that the text will be interpolated using
1631               exactly the same rules as normal double quoted strings.
1632
1633                      print <<EOF;
1634                   The price is $Price.
1635                   EOF
1636
1637                      print << "EOF"; # same as above
1638                   The price is $Price.
1639                   EOF
1640
1641           Single Quotes
1642               Single quotes indicate the text is to be treated literally with
1643               no interpolation of its content. This is similar to single
1644               quoted strings except that backslashes have no special meaning,
1645               with "\\" being treated as two backslashes and not one as they
1646               would in every other quoting construct.
1647
1648               This is the only form of quoting in perl where there is no need
1649               to worry about escaping content, something that code generators
1650               can and do make good use of.
1651
1652           Backticks
1653               The content of the here doc is treated just as it would be if
1654               the string were embedded in backticks. Thus the content is
1655               interpolated as though it were double quoted and then executed
1656               via the shell, with the results of the execution returned.
1657
1658                      print << `EOC`; # execute command and get results
1659                   echo hi there
1660                   EOC
1661
1662           It is possible to stack multiple here-docs in a row:
1663
1664                  print <<"foo", <<"bar"; # you can stack them
1665               I said foo.
1666               foo
1667               I said bar.
1668               bar
1669
1670                  myfunc(<< "THIS", 23, <<'THAT');
1671               Here's a line
1672               or two.
1673               THIS
1674               and here's another.
1675               THAT
1676
1677           Just don't forget that you have to put a semicolon on the end to
1678           finish the statement, as Perl doesn't know you're not going to try
1679           to do this:
1680
1681                  print <<ABC
1682               179231
1683               ABC
1684                  + 20;
1685
1686           If you want to remove the line terminator from your here-docs, use
1687           "chomp()".
1688
1689               chomp($string = <<'END');
1690               This is a string.
1691               END
1692
1693           If you want your here-docs to be indented with the rest of the
1694           code, you'll need to remove leading whitespace from each line
1695           manually:
1696
1697               ($quote = <<'FINIS') =~ s/^\s+//gm;
1698                  The Road goes ever on and on,
1699                  down from the door where it began.
1700               FINIS
1701
1702           If you use a here-doc within a delimited construct, such as in
1703           "s///eg", the quoted material must come on the lines following the
1704           final delimiter.  So instead of
1705
1706               s/this/<<E . 'that'
1707               the other
1708               E
1709                . 'more '/eg;
1710
1711           you have to write
1712
1713               s/this/<<E . 'that'
1714                . 'more '/eg;
1715               the other
1716               E
1717
1718           If the terminating identifier is on the last line of the program,
1719           you must be sure there is a newline after it; otherwise, Perl will
1720           give the warning Can't find string terminator "END" anywhere before
1721           EOF....
1722
1723           Additionally, the quoting rules for the end of string identifier
1724           are not related to Perl's quoting rules. "q()", "qq()", and the
1725           like are not supported in place of '' and "", and the only
1726           interpolation is for backslashing the quoting character:
1727
1728               print << "abc\"def";
1729               testing...
1730               abc"def
1731
1732           Finally, quoted strings cannot span multiple lines.  The general
1733           rule is that the identifier must be a string literal.  Stick with
1734           that, and you should be safe.
1735
1736   Gory details of parsing quoted constructs
1737       When presented with something that might have several different
1738       interpretations, Perl uses the DWIM (that's "Do What I Mean") principle
1739       to pick the most probable interpretation.  This strategy is so
1740       successful that Perl programmers often do not suspect the ambivalence
1741       of what they write.  But from time to time, Perl's notions differ
1742       substantially from what the author honestly meant.
1743
1744       This section hopes to clarify how Perl handles quoted constructs.
1745       Although the most common reason to learn this is to unravel
1746       labyrinthine regular expressions, because the initial steps of parsing
1747       are the same for all quoting operators, they are all discussed
1748       together.
1749
1750       The most important Perl parsing rule is the first one discussed below:
1751       when processing a quoted construct, Perl first finds the end of that
1752       construct, then interprets its contents.  If you understand this rule,
1753       you may skip the rest of this section on the first reading.  The other
1754       rules are likely to contradict the user's expectations much less
1755       frequently than this first one.
1756
1757       Some passes discussed below are performed concurrently, but because
1758       their results are the same, we consider them individually.  For
1759       different quoting constructs, Perl performs different numbers of
1760       passes, from one to four, but these passes are always performed in the
1761       same order.
1762
1763       Finding the end
1764           The first pass is finding the end of the quoted construct, where
1765           the information about the delimiters is used in parsing.  During
1766           this search, text between the starting and ending delimiters is
1767           copied to a safe location. The text copied gets delimiter-
1768           independent.
1769
1770           If the construct is a here-doc, the ending delimiter is a line that
1771           has a terminating string as the content. Therefore "<<EOF" is
1772           terminated by "EOF" immediately followed by "\n" and starting from
1773           the first column of the terminating line.  When searching for the
1774           terminating line of a here-doc, nothing is skipped. In other words,
1775           lines after the here-doc syntax are compared with the terminating
1776           string line by line.
1777
1778           For the constructs except here-docs, single characters are used as
1779           starting and ending delimiters. If the starting delimiter is an
1780           opening punctuation (that is "(", "[", "{", or "<"), the ending
1781           delimiter is the corresponding closing punctuation (that is ")",
1782           "]", "}", or ">").  If the starting delimiter is an unpaired
1783           character like "/" or a closing punctuation, the ending delimiter
1784           is same as the starting delimiter.  Therefore a "/" terminates a
1785           "qq//" construct, while a "]" terminates "qq[]" and "qq]]"
1786           constructs.
1787
1788           When searching for single-character delimiters, escaped delimiters
1789           and "\\" are skipped. For example, while searching for terminating
1790           "/", combinations of "\\" and "\/" are skipped.  If the delimiters
1791           are bracketing, nested pairs are also skipped.  For example, while
1792           searching for closing "]" paired with the opening "[", combinations
1793           of "\\", "\]", and "\[" are all skipped, and nested "[" and "]" are
1794           skipped as well.  However, when backslashes are used as the
1795           delimiters (like "qq\\" and "tr\\\"), nothing is skipped.  During
1796           the search for the end, backslashes that escape delimiters are
1797           removed (exactly speaking, they are not copied to the safe
1798           location).
1799
1800           For constructs with three-part delimiters ("s///", "y///", and
1801           "tr///"), the search is repeated once more.  If the first delimiter
1802           is not an opening punctuation, three delimiters must be same such
1803           as "s!!!" and "tr)))", in which case the second delimiter
1804           terminates the left part and starts the right part at once.  If the
1805           left part is delimited by bracketing punctuations (that is "()",
1806           "[]", "{}", or "<>"), the right part needs another pair of
1807           delimiters such as "s(){}" and "tr[]//".  In these cases,
1808           whitespaces and comments are allowed between both parts, though the
1809           comment must follow at least one whitespace; otherwise a character
1810           expected as the start of the comment may be regarded as the
1811           starting delimiter of the right part.
1812
1813           During this search no attention is paid to the semantics of the
1814           construct.  Thus:
1815
1816               "$hash{"$foo/$bar"}"
1817
1818           or:
1819
1820               m/
1821                 bar       # NOT a comment, this slash / terminated m//!
1822                /x
1823
1824           do not form legal quoted expressions.   The quoted part ends on the
1825           first """ and "/", and the rest happens to be a syntax error.
1826           Because the slash that terminated "m//" was followed by a "SPACE",
1827           the example above is not "m//x", but rather "m//" with no "/x"
1828           modifier.  So the embedded "#" is interpreted as a literal "#".
1829
1830           Also no attention is paid to "\c\" (multichar control char syntax)
1831           during this search. Thus the second "\" in "qq/\c\/" is interpreted
1832           as a part of "\/", and the following "/" is not recognized as a
1833           delimiter.  Instead, use "\034" or "\x1c" at the end of quoted
1834           constructs.
1835
1836       Interpolation
1837           The next step is interpolation in the text obtained, which is now
1838           delimiter-independent.  There are multiple cases.
1839
1840           "<<'EOF'"
1841               No interpolation is performed.  Note that the combination "\\"
1842               is left intact, since escaped delimiters are not available for
1843               here-docs.
1844
1845           "m''", the pattern of "s'''"
1846               No interpolation is performed at this stage.  Any backslashed
1847               sequences including "\\" are treated at the stage to "parsing
1848               regular expressions".
1849
1850           '', "q//", "tr'''", "y'''", the replacement of "s'''"
1851               The only interpolation is removal of "\" from pairs of "\\".
1852               Therefore "-" in "tr'''" and "y'''" is treated literally as a
1853               hyphen and no character range is available.  "\1" in the
1854               replacement of "s'''" does not work as $1.
1855
1856           "tr///", "y///"
1857               No variable interpolation occurs.  String modifying
1858               combinations for case and quoting such as "\Q", "\U", and "\E"
1859               are not recognized.  The other escape sequences such as "\200"
1860               and "\t" and backslashed characters such as "\\" and "\-" are
1861               converted to appropriate literals.  The character "-" is
1862               treated specially and therefore "\-" is treated as a literal
1863               "-".
1864
1865           "", "``", "qq//", "qx//", "<file*glob>", "<<"EOF""
1866               "\Q", "\U", "\u", "\L", "\l" (possibly paired with "\E") are
1867               converted to corresponding Perl constructs.  Thus,
1868               "$foo\Qbaz$bar" is converted to "$foo . (quotemeta("baz" .
1869               $bar))" internally.  The other escape sequences such as "\200"
1870               and "\t" and backslashed characters such as "\\" and "\-" are
1871               replaced with appropriate expansions.
1872
1873               Let it be stressed that whatever falls between "\Q" and "\E" is
1874               interpolated in the usual way.  Something like "\Q\\E" has no
1875               "\E" inside.  instead, it has "\Q", "\\", and "E", so the
1876               result is the same as for "\\\\E".  As a general rule,
1877               backslashes between "\Q" and "\E" may lead to counterintuitive
1878               results.  So, "\Q\t\E" is converted to "quotemeta("\t")", which
1879               is the same as "\\\t" (since TAB is not alphanumeric).  Note
1880               also that:
1881
1882                 $str = '\t';
1883                 return "\Q$str";
1884
1885               may be closer to the conjectural intention of the writer of
1886               "\Q\t\E".
1887
1888               Interpolated scalars and arrays are converted internally to the
1889               "join" and "." catenation operations.  Thus, "$foo XXX '@arr'"
1890               becomes:
1891
1892                 $foo . " XXX '" . (join $", @arr) . "'";
1893
1894               All operations above are performed simultaneously, left to
1895               right.
1896
1897               Because the result of "\Q STRING \E" has all metacharacters
1898               quoted, there is no way to insert a literal "$" or "@" inside a
1899               "\Q\E" pair.  If protected by "\", "$" will be quoted to became
1900               "\\\$"; if not, it is interpreted as the start of an
1901               interpolated scalar.
1902
1903               Note also that the interpolation code needs to make a decision
1904               on where the interpolated scalar ends.  For instance, whether
1905               "a $b -> {c}" really means:
1906
1907                 "a " . $b . " -> {c}";
1908
1909               or:
1910
1911                 "a " . $b -> {c};
1912
1913               Most of the time, the longest possible text that does not
1914               include spaces between components and which contains matching
1915               braces or brackets.  because the outcome may be determined by
1916               voting based on heuristic estimators, the result is not
1917               strictly predictable.  Fortunately, it's usually correct for
1918               ambiguous cases.
1919
1920           the replacement of "s///"
1921               Processing of "\Q", "\U", "\u", "\L", "\l", and interpolation
1922               happens as with "qq//" constructs.
1923
1924               It is at this step that "\1" is begrudgingly converted to $1 in
1925               the replacement text of "s///", in order to correct the
1926               incorrigible sed hackers who haven't picked up the saner idiom
1927               yet.  A warning is emitted if the "use warnings" pragma or the
1928               -w command-line flag (that is, the $^W variable) was set.
1929
1930           "RE" in "?RE?", "/RE/", "m/RE/", "s/RE/foo/",
1931               Processing of "\Q", "\U", "\u", "\L", "\l", "\E", and
1932               interpolation happens (almost) as with "qq//" constructs.
1933
1934               Processing of "\N{...}" is also done here, and compiled into an
1935               intermediate form for the regex compiler.  (This is because, as
1936               mentioned below, the regex compilation may be done at execution
1937               time, and "\N{...}" is a compile-time construct.)
1938
1939               However any other combinations of "\" followed by a character
1940               are not substituted but only skipped, in order to parse them as
1941               regular expressions at the following step.  As "\c" is skipped
1942               at this step, "@" of "\c@" in RE is possibly treated as an
1943               array symbol (for example @foo), even though the same text in
1944               "qq//" gives interpolation of "\c@".
1945
1946               Moreover, inside "(?{BLOCK})", "(?# comment )", and a
1947               "#"-comment in a "//x"-regular expression, no processing is
1948               performed whatsoever.  This is the first step at which the
1949               presence of the "//x" modifier is relevant.
1950
1951               Interpolation in patterns has several quirks: $|, $(, $), "@+"
1952               and "@-" are not interpolated, and constructs $var[SOMETHING]
1953               are voted (by several different estimators) to be either an
1954               array element or $var followed by an RE alternative.  This is
1955               where the notation "${arr[$bar]}" comes handy: "/${arr[0-9]}/"
1956               is interpreted as array element "-9", not as a regular
1957               expression from the variable $arr followed by a digit, which
1958               would be the interpretation of "/$arr[0-9]/".  Since voting
1959               among different estimators may occur, the result is not
1960               predictable.
1961
1962               The lack of processing of "\\" creates specific restrictions on
1963               the post-processed text.  If the delimiter is "/", one cannot
1964               get the combination "\/" into the result of this step.  "/"
1965               will finish the regular expression, "\/" will be stripped to
1966               "/" on the previous step, and "\\/" will be left as is.
1967               Because "/" is equivalent to "\/" inside a regular expression,
1968               this does not matter unless the delimiter happens to be
1969               character special to the RE engine, such as in "s*foo*bar*",
1970               "m[foo]", or "?foo?"; or an alphanumeric char, as in:
1971
1972                 m m ^ a \s* b mmx;
1973
1974               In the RE above, which is intentionally obfuscated for
1975               illustration, the delimiter is "m", the modifier is "mx", and
1976               after delimiter-removal the RE is the same as for "m/ ^ a \s* b
1977               /mx".  There's more than one reason you're encouraged to
1978               restrict your delimiters to non-alphanumeric, non-whitespace
1979               choices.
1980
1981           This step is the last one for all constructs except regular
1982           expressions, which are processed further.
1983
1984       parsing regular expressions
1985           Previous steps were performed during the compilation of Perl code,
1986           but this one happens at run time, although it may be optimized to
1987           be calculated at compile time if appropriate.  After preprocessing
1988           described above, and possibly after evaluation if concatenation,
1989           joining, casing translation, or metaquoting are involved, the
1990           resulting string is passed to the RE engine for compilation.
1991
1992           Whatever happens in the RE engine might be better discussed in
1993           perlre, but for the sake of continuity, we shall do so here.
1994
1995           This is another step where the presence of the "//x" modifier is
1996           relevant.  The RE engine scans the string from left to right and
1997           converts it to a finite automaton.
1998
1999           Backslashed characters are either replaced with corresponding
2000           literal strings (as with "\{"), or else they generate special nodes
2001           in the finite automaton (as with "\b").  Characters special to the
2002           RE engine (such as "|") generate corresponding nodes or groups of
2003           nodes.  "(?#...)" comments are ignored.  All the rest is either
2004           converted to literal strings to match, or else is ignored (as is
2005           whitespace and "#"-style comments if "//x" is present).
2006
2007           Parsing of the bracketed character class construct, "[...]", is
2008           rather different than the rule used for the rest of the pattern.
2009           The terminator of this construct is found using the same rules as
2010           for finding the terminator of a "{}"-delimited construct, the only
2011           exception being that "]" immediately following "[" is treated as
2012           though preceded by a backslash.  Similarly, the terminator of
2013           "(?{...})" is found using the same rules as for finding the
2014           terminator of a "{}"-delimited construct.
2015
2016           It is possible to inspect both the string given to RE engine and
2017           the resulting finite automaton.  See the arguments
2018           "debug"/"debugcolor" in the "use re" pragma, as well as Perl's -Dr
2019           command-line switch documented in "Command Switches" in perlrun.
2020
2021       Optimization of regular expressions
2022           This step is listed for completeness only.  Since it does not
2023           change semantics, details of this step are not documented and are
2024           subject to change without notice.  This step is performed over the
2025           finite automaton that was generated during the previous pass.
2026
2027           It is at this stage that "split()" silently optimizes "/^/" to mean
2028           "/^/m".
2029
2030   I/O Operators
2031       There are several I/O operators you should know about.
2032
2033       A string enclosed by backticks (grave accents) first undergoes double-
2034       quote interpolation.  It is then interpreted as an external command,
2035       and the output of that command is the value of the backtick string,
2036       like in a shell.  In scalar context, a single string consisting of all
2037       output is returned.  In list context, a list of values is returned, one
2038       per line of output.  (You can set $/ to use a different line
2039       terminator.)  The command is executed each time the pseudo-literal is
2040       evaluated.  The status value of the command is returned in $? (see
2041       perlvar for the interpretation of $?).  Unlike in csh, no translation
2042       is done on the return data--newlines remain newlines.  Unlike in any of
2043       the shells, single quotes do not hide variable names in the command
2044       from interpretation.  To pass a literal dollar-sign through to the
2045       shell you need to hide it with a backslash.  The generalized form of
2046       backticks is "qx//".  (Because backticks always undergo shell expansion
2047       as well, see perlsec for security concerns.)
2048
2049       In scalar context, evaluating a filehandle in angle brackets yields the
2050       next line from that file (the newline, if any, included), or "undef" at
2051       end-of-file or on error.  When $/ is set to "undef" (sometimes known as
2052       file-slurp mode) and the file is empty, it returns '' the first time,
2053       followed by "undef" subsequently.
2054
2055       Ordinarily you must assign the returned value to a variable, but there
2056       is one situation where an automatic assignment happens.  If and only if
2057       the input symbol is the only thing inside the conditional of a "while"
2058       statement (even if disguised as a "for(;;)" loop), the value is
2059       automatically assigned to the global variable $_, destroying whatever
2060       was there previously.  (This may seem like an odd thing to you, but
2061       you'll use the construct in almost every Perl script you write.)  The
2062       $_ variable is not implicitly localized.  You'll have to put a "local
2063       $_;" before the loop if you want that to happen.
2064
2065       The following lines are equivalent:
2066
2067           while (defined($_ = <STDIN>)) { print; }
2068           while ($_ = <STDIN>) { print; }
2069           while (<STDIN>) { print; }
2070           for (;<STDIN>;) { print; }
2071           print while defined($_ = <STDIN>);
2072           print while ($_ = <STDIN>);
2073           print while <STDIN>;
2074
2075       This also behaves similarly, but avoids $_ :
2076
2077           while (my $line = <STDIN>) { print $line }
2078
2079       In these loop constructs, the assigned value (whether assignment is
2080       automatic or explicit) is then tested to see whether it is defined.
2081       The defined test avoids problems where line has a string value that
2082       would be treated as false by Perl, for example a "" or a "0" with no
2083       trailing newline.  If you really mean for such values to terminate the
2084       loop, they should be tested for explicitly:
2085
2086           while (($_ = <STDIN>) ne '0') { ... }
2087           while (<STDIN>) { last unless $_; ... }
2088
2089       In other boolean contexts, "<filehandle>" without an explicit "defined"
2090       test or comparison elicits a warning if the "use warnings" pragma or
2091       the -w command-line switch (the $^W variable) is in effect.
2092
2093       The filehandles STDIN, STDOUT, and STDERR are predefined.  (The
2094       filehandles "stdin", "stdout", and "stderr" will also work except in
2095       packages, where they would be interpreted as local identifiers rather
2096       than global.)  Additional filehandles may be created with the open()
2097       function, amongst others.  See perlopentut and "open" in perlfunc for
2098       details on this.
2099
2100       If a <FILEHANDLE> is used in a context that is looking for a list, a
2101       list comprising all input lines is returned, one line per list element.
2102       It's easy to grow to a rather large data space this way, so use with
2103       care.
2104
2105       <FILEHANDLE> may also be spelled "readline(*FILEHANDLE)".  See
2106       "readline" in perlfunc.
2107
2108       The null filehandle <> is special: it can be used to emulate the
2109       behavior of sed and awk.  Input from <> comes either from standard
2110       input, or from each file listed on the command line.  Here's how it
2111       works: the first time <> is evaluated, the @ARGV array is checked, and
2112       if it is empty, $ARGV[0] is set to "-", which when opened gives you
2113       standard input.  The @ARGV array is then processed as a list of
2114       filenames.  The loop
2115
2116           while (<>) {
2117               ...                     # code for each line
2118           }
2119
2120       is equivalent to the following Perl-like pseudo code:
2121
2122           unshift(@ARGV, '-') unless @ARGV;
2123           while ($ARGV = shift) {
2124               open(ARGV, $ARGV);
2125               while (<ARGV>) {
2126                   ...         # code for each line
2127               }
2128           }
2129
2130       except that it isn't so cumbersome to say, and will actually work.  It
2131       really does shift the @ARGV array and put the current filename into the
2132       $ARGV variable.  It also uses filehandle ARGV internally. <> is just a
2133       synonym for <ARGV>, which is magical.  (The pseudo code above doesn't
2134       work because it treats <ARGV> as non-magical.)
2135
2136       Since the null filehandle uses the two argument form of "open" in
2137       perlfunc it interprets special characters, so if you have a script like
2138       this:
2139
2140           while (<>) {
2141               print;
2142           }
2143
2144       and call it with "perl dangerous.pl 'rm -rfv *|'", it actually opens a
2145       pipe, executes the "rm" command and reads "rm"'s output from that pipe.
2146       If you want all items in @ARGV to be interpreted as file names, you can
2147       use the module "ARGV::readonly" from CPAN.
2148
2149       You can modify @ARGV before the first <> as long as the array ends up
2150       containing the list of filenames you really want.  Line numbers ($.)
2151       continue as though the input were one big happy file.  See the example
2152       in "eof" in perlfunc for how to reset line numbers on each file.
2153
2154       If you want to set @ARGV to your own list of files, go right ahead.
2155       This sets @ARGV to all plain text files if no @ARGV was given:
2156
2157           @ARGV = grep { -f && -T } glob('*') unless @ARGV;
2158
2159       You can even set them to pipe commands.  For example, this
2160       automatically filters compressed arguments through gzip:
2161
2162           @ARGV = map { /\.(gz|Z)$/ ? "gzip -dc < $_ |" : $_ } @ARGV;
2163
2164       If you want to pass switches into your script, you can use one of the
2165       Getopts modules or put a loop on the front like this:
2166
2167           while ($_ = $ARGV[0], /^-/) {
2168               shift;
2169               last if /^--$/;
2170               if (/^-D(.*)/) { $debug = $1 }
2171               if (/^-v/)     { $verbose++  }
2172               # ...           # other switches
2173           }
2174
2175           while (<>) {
2176               # ...           # code for each line
2177           }
2178
2179       The <> symbol will return "undef" for end-of-file only once.  If you
2180       call it again after this, it will assume you are processing another
2181       @ARGV list, and if you haven't set @ARGV, will read input from STDIN.
2182
2183       If what the angle brackets contain is a simple scalar variable (e.g.,
2184       <$foo>), then that variable contains the name of the filehandle to
2185       input from, or its typeglob, or a reference to the same.  For example:
2186
2187           $fh = \*STDIN;
2188           $line = <$fh>;
2189
2190       If what's within the angle brackets is neither a filehandle nor a
2191       simple scalar variable containing a filehandle name, typeglob, or
2192       typeglob reference, it is interpreted as a filename pattern to be
2193       globbed, and either a list of filenames or the next filename in the
2194       list is returned, depending on context.  This distinction is determined
2195       on syntactic grounds alone.  That means "<$x>" is always a readline()
2196       from an indirect handle, but "<$hash{key}>" is always a glob().  That's
2197       because $x is a simple scalar variable, but $hash{key} is not--it's a
2198       hash element.  Even "<$x >" (note the extra space) is treated as
2199       "glob("$x ")", not "readline($x)".
2200
2201       One level of double-quote interpretation is done first, but you can't
2202       say "<$foo>" because that's an indirect filehandle as explained in the
2203       previous paragraph.  (In older versions of Perl, programmers would
2204       insert curly brackets to force interpretation as a filename glob:
2205       "<${foo}>".  These days, it's considered cleaner to call the internal
2206       function directly as "glob($foo)", which is probably the right way to
2207       have done it in the first place.)  For example:
2208
2209           while (<*.c>) {
2210               chmod 0644, $_;
2211           }
2212
2213       is roughly equivalent to:
2214
2215           open(FOO, "echo *.c | tr -s ' \t\r\f' '\\012\\012\\012\\012'|");
2216           while (<FOO>) {
2217               chomp;
2218               chmod 0644, $_;
2219           }
2220
2221       except that the globbing is actually done internally using the standard
2222       "File::Glob" extension.  Of course, the shortest way to do the above
2223       is:
2224
2225           chmod 0644, <*.c>;
2226
2227       A (file)glob evaluates its (embedded) argument only when it is starting
2228       a new list.  All values must be read before it will start over.  In
2229       list context, this isn't important because you automatically get them
2230       all anyway.  However, in scalar context the operator returns the next
2231       value each time it's called, or "undef" when the list has run out.  As
2232       with filehandle reads, an automatic "defined" is generated when the
2233       glob occurs in the test part of a "while", because legal glob returns
2234       (e.g. a file called 0) would otherwise terminate the loop.  Again,
2235       "undef" is returned only once.  So if you're expecting a single value
2236       from a glob, it is much better to say
2237
2238           ($file) = <blurch*>;
2239
2240       than
2241
2242           $file = <blurch*>;
2243
2244       because the latter will alternate between returning a filename and
2245       returning false.
2246
2247       If you're trying to do variable interpolation, it's definitely better
2248       to use the glob() function, because the older notation can cause people
2249       to become confused with the indirect filehandle notation.
2250
2251           @files = glob("$dir/*.[ch]");
2252           @files = glob($files[$i]);
2253
2254   Constant Folding
2255       Like C, Perl does a certain amount of expression evaluation at compile
2256       time whenever it determines that all arguments to an operator are
2257       static and have no side effects.  In particular, string concatenation
2258       happens at compile time between literals that don't do variable
2259       substitution.  Backslash interpolation also happens at compile time.
2260       You can say
2261
2262           'Now is the time for all' . "\n" .
2263               'good men to come to.'
2264
2265       and this all reduces to one string internally.  Likewise, if you say
2266
2267           foreach $file (@filenames) {
2268               if (-s $file > 5 + 100 * 2**16) {  }
2269           }
2270
2271       the compiler will precompute the number which that expression
2272       represents so that the interpreter won't have to.
2273
2274   No-ops
2275       Perl doesn't officially have a no-op operator, but the bare constants 0
2276       and 1 are special-cased to not produce a warning in a void context, so
2277       you can for example safely do
2278
2279           1 while foo();
2280
2281   Bitwise String Operators
2282       Bitstrings of any size may be manipulated by the bitwise operators ("~
2283       | & ^").
2284
2285       If the operands to a binary bitwise op are strings of different sizes,
2286       | and ^ ops act as though the shorter operand had additional zero bits
2287       on the right, while the & op acts as though the longer operand were
2288       truncated to the length of the shorter.  The granularity for such
2289       extension or truncation is one or more bytes.
2290
2291           # ASCII-based examples
2292           print "j p \n" ^ " a h";            # prints "JAPH\n"
2293           print "JA" | "  ph\n";              # prints "japh\n"
2294           print "japh\nJunk" & '_____';       # prints "JAPH\n";
2295           print 'p N$' ^ " E<H\n";            # prints "Perl\n";
2296
2297       If you are intending to manipulate bitstrings, be certain that you're
2298       supplying bitstrings: If an operand is a number, that will imply a
2299       numeric bitwise operation.  You may explicitly show which type of
2300       operation you intend by using "" or "0+", as in the examples below.
2301
2302           $foo =  150  |  105;        # yields 255  (0x96 | 0x69 is 0xFF)
2303           $foo = '150' |  105;        # yields 255
2304           $foo =  150  | '105';       # yields 255
2305           $foo = '150' | '105';       # yields string '155' (under ASCII)
2306
2307           $baz = 0+$foo & 0+$bar;     # both ops explicitly numeric
2308           $biz = "$foo" ^ "$bar";     # both ops explicitly stringy
2309
2310       See "vec" in perlfunc for information on how to manipulate individual
2311       bits in a bit vector.
2312
2313   Integer Arithmetic
2314       By default, Perl assumes that it must do most of its arithmetic in
2315       floating point.  But by saying
2316
2317           use integer;
2318
2319       you may tell the compiler that it's okay to use integer operations (if
2320       it feels like it) from here to the end of the enclosing BLOCK.  An
2321       inner BLOCK may countermand this by saying
2322
2323           no integer;
2324
2325       which lasts until the end of that BLOCK.  Note that this doesn't mean
2326       everything is only an integer, merely that Perl may use integer
2327       operations if it is so inclined.  For example, even under "use
2328       integer", if you take the sqrt(2), you'll still get 1.4142135623731 or
2329       so.
2330
2331       Used on numbers, the bitwise operators ("&", "|", "^", "~", "<<", and
2332       ">>") always produce integral results.  (But see also "Bitwise String
2333       Operators".)  However, "use integer" still has meaning for them.  By
2334       default, their results are interpreted as unsigned integers, but if
2335       "use integer" is in effect, their results are interpreted as signed
2336       integers.  For example, "~0" usually evaluates to a large integral
2337       value.  However, "use integer; ~0" is "-1" on two's-complement
2338       machines.
2339
2340   Floating-point Arithmetic
2341       While "use integer" provides integer-only arithmetic, there is no
2342       analogous mechanism to provide automatic rounding or truncation to a
2343       certain number of decimal places.  For rounding to a certain number of
2344       digits, sprintf() or printf() is usually the easiest route.  See
2345       perlfaq4.
2346
2347       Floating-point numbers are only approximations to what a mathematician
2348       would call real numbers.  There are infinitely more reals than floats,
2349       so some corners must be cut.  For example:
2350
2351           printf "%.20g\n", 123456789123456789;
2352           #        produces 123456789123456784
2353
2354       Testing for exact floating-point equality or inequality is not a good
2355       idea.  Here's a (relatively expensive) work-around to compare whether
2356       two floating-point numbers are equal to a particular number of decimal
2357       places.  See Knuth, volume II, for a more robust treatment of this
2358       topic.
2359
2360           sub fp_equal {
2361               my ($X, $Y, $POINTS) = @_;
2362               my ($tX, $tY);
2363               $tX = sprintf("%.${POINTS}g", $X);
2364               $tY = sprintf("%.${POINTS}g", $Y);
2365               return $tX eq $tY;
2366           }
2367
2368       The POSIX module (part of the standard perl distribution) implements
2369       ceil(), floor(), and other mathematical and trigonometric functions.
2370       The Math::Complex module (part of the standard perl distribution)
2371       defines mathematical functions that work on both the reals and the
2372       imaginary numbers.  Math::Complex not as efficient as POSIX, but POSIX
2373       can't work with complex numbers.
2374
2375       Rounding in financial applications can have serious implications, and
2376       the rounding method used should be specified precisely.  In these
2377       cases, it probably pays not to trust whichever system rounding is being
2378       used by Perl, but to instead implement the rounding function you need
2379       yourself.
2380
2381   Bigger Numbers
2382       The standard Math::BigInt and Math::BigFloat modules provide variable-
2383       precision arithmetic and overloaded operators, although they're
2384       currently pretty slow. At the cost of some space and considerable
2385       speed, they avoid the normal pitfalls associated with limited-precision
2386       representations.
2387
2388           use Math::BigInt;
2389           $x = Math::BigInt->new('123456789123456789');
2390           print $x * $x;
2391
2392           # prints +15241578780673678515622620750190521
2393
2394       There are several modules that let you calculate with (bound only by
2395       memory and cpu-time) unlimited or fixed precision. There are also some
2396       non-standard modules that provide faster implementations via external C
2397       libraries.
2398
2399       Here is a short, but incomplete summary:
2400
2401               Math::Fraction          big, unlimited fractions like 9973 / 12967
2402               Math::String            treat string sequences like numbers
2403               Math::FixedPrecision    calculate with a fixed precision
2404               Math::Currency          for currency calculations
2405               Bit::Vector             manipulate bit vectors fast (uses C)
2406               Math::BigIntFast        Bit::Vector wrapper for big numbers
2407               Math::Pari              provides access to the Pari C library
2408               Math::BigInteger        uses an external C library
2409               Math::Cephes            uses external Cephes C library (no big numbers)
2410               Math::Cephes::Fraction  fractions via the Cephes library
2411               Math::GMP               another one using an external C library
2412
2413       Choose wisely.
2414
2415
2416
2417perl v5.12.4                      2011-06-07                         PERLOP(1)
Impressum