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

NAME

6       perlop - Perl operators and precedence
7

DESCRIPTION

9       In Perl, the operator determines what operation is performed,
10       independent of the type of the operands.  For example "$x + $y" is
11       always a numeric addition, and if $x or $y do not contain numbers, an
12       attempt is made to convert them to numbers first.
13
14       This is in contrast to many other dynamic languages, where the
15       operation is determined by the type of the first argument.  It also
16       means that Perl has two versions of some operators, one for numeric and
17       one for string comparison.  For example "$x == $y" compares two numbers
18       for equality, and "$x eq $y" compares two strings.
19
20       There are a few exceptions though: "x" can be either string repetition
21       or list repetition, depending on the type of the left operand, and "&",
22       "|", "^" and "~" can be either string or numeric bit operations.
23
24   Operator Precedence and Associativity
25       Operator precedence and associativity work in Perl more or less like
26       they do in mathematics.
27
28       Operator precedence means some operators are evaluated before others.
29       For example, in "2 + 4 * 5", the multiplication has higher precedence
30       so "4 * 5" is evaluated first yielding "2 + 20 == 22" and not
31       "6 * 5 == 30".
32
33       Operator associativity defines what happens if a sequence of the same
34       operators is used one after another: whether the evaluator will
35       evaluate the left operations first, or the right first.  For example,
36       in "8 - 4 - 2", subtraction is left associative so Perl evaluates the
37       expression left to right.  "8 - 4" is evaluated first making the
38       expression "4 - 2 == 2" and not "8 - 2 == 6".
39
40       Perl operators have the following associativity and precedence, listed
41       from highest precedence to lowest.  Operators borrowed from C keep the
42       same precedence relationship with each other, even where C's precedence
43       is slightly screwy.  (This makes learning Perl easier for C folks.)
44       With very few exceptions, these all operate on scalar values only, not
45       array values.
46
47           left        terms and list operators (leftward)
48           left        ->
49           nonassoc    ++ --
50           right       **
51           right       ! ~ \ and unary + and -
52           left        =~ !~
53           left        * / % x
54           left        + - .
55           left        << >>
56           nonassoc    named unary operators
57           nonassoc    < > <= >= lt gt le ge
58           nonassoc    == != <=> eq ne cmp ~~
59           left        &
60           left        | ^
61           left        &&
62           left        || //
63           nonassoc    ..  ...
64           right       ?:
65           right       = += -= *= etc. goto last next redo dump
66           left        , =>
67           nonassoc    list operators (rightward)
68           right       not
69           left        and
70           left        or xor
71
72       In the following sections, these operators are covered in detail, in
73       the same order in which they appear in the table above.
74
75       Many operators can be overloaded for objects.  See overload.
76
77   Terms and List Operators (Leftward)
78       A TERM has the highest precedence in Perl.  They include variables,
79       quote and quote-like operators, any expression in parentheses, and any
80       function whose arguments are parenthesized.  Actually, there aren't
81       really functions in this sense, just list operators and unary operators
82       behaving as functions because you put parentheses around the arguments.
83       These are all documented in perlfunc.
84
85       If any list operator ("print()", etc.) or any unary operator
86       ("chdir()", etc.)  is followed by a left parenthesis as the next token,
87       the operator and arguments within parentheses are taken to be of
88       highest precedence, just like a normal function call.
89
90       In the absence of parentheses, the precedence of list operators such as
91       "print", "sort", or "chmod" is either very high or very low depending
92       on whether you are looking at the left side or the right side of the
93       operator.  For example, in
94
95           @ary = (1, 3, sort 4, 2);
96           print @ary;         # prints 1324
97
98       the commas on the right of the "sort" are evaluated before the "sort",
99       but the commas on the left are evaluated after.  In other words, list
100       operators tend to gobble up all arguments that follow, and then act
101       like a simple TERM with regard to the preceding expression.  Be careful
102       with parentheses:
103
104           # These evaluate exit before doing the print:
105           print($foo, exit);  # Obviously not what you want.
106           print $foo, exit;   # Nor is this.
107
108           # These do the print before evaluating exit:
109           (print $foo), exit; # This is what you want.
110           print($foo), exit;  # Or this.
111           print ($foo), exit; # Or even this.
112
113       Also note that
114
115           print ($foo & 255) + 1, "\n";
116
117       probably doesn't do what you expect at first glance.  The parentheses
118       enclose the argument list for "print" which is evaluated (printing the
119       result of "$foo & 255").  Then one is added to the return value of
120       "print" (usually 1).  The result is something like this:
121
122           1 + 1, "\n";    # Obviously not what you meant.
123
124       To do what you meant properly, you must write:
125
126           print(($foo & 255) + 1, "\n");
127
128       See "Named Unary Operators" for more discussion of this.
129
130       Also parsed as terms are the "do {}" and "eval {}" constructs, as well
131       as subroutine and method calls, and the anonymous constructors "[]" and
132       "{}".
133
134       See also "Quote and Quote-like Operators" toward the end of this
135       section, as well as "I/O Operators".
136
137   The Arrow Operator
138       ""->"" is an infix dereference operator, just as it is in C and C++.
139       If the right side is either a "[...]", "{...}", or a "(...)" subscript,
140       then the left side must be either a hard or symbolic reference to an
141       array, a hash, or a subroutine respectively.  (Or technically speaking,
142       a location capable of holding a hard reference, if it's an array or
143       hash reference being used for assignment.)  See perlreftut and perlref.
144
145       Otherwise, the right side is a method name or a simple scalar variable
146       containing either the method name or a subroutine reference, and the
147       left side must be either an object (a blessed reference) or a class
148       name (that is, a package name).  See perlobj.
149
150       The dereferencing cases (as opposed to method-calling cases) are
151       somewhat extended by the "postderef" feature.  For the details of that
152       feature, consult "Postfix Dereference Syntax" in perlref.
153
154   Auto-increment and Auto-decrement
155       "++" and "--" work as in C.  That is, if placed before a variable, they
156       increment or decrement the variable by one before returning the value,
157       and if placed after, increment or decrement after returning the value.
158
159           $i = 0;  $j = 0;
160           print $i++;  # prints 0
161           print ++$j;  # prints 1
162
163       Note that just as in C, Perl doesn't define when the variable is
164       incremented or decremented.  You just know it will be done sometime
165       before or after the value is returned.  This also means that modifying
166       a variable twice in the same statement will lead to undefined behavior.
167       Avoid statements like:
168
169           $i = $i ++;
170           print ++ $i + $i ++;
171
172       Perl will not guarantee what the result of the above statements is.
173
174       The auto-increment operator has a little extra builtin magic to it.  If
175       you increment a variable that is numeric, or that has ever been used in
176       a numeric context, you get a normal increment.  If, however, the
177       variable has been used in only string contexts since it was set, and
178       has a value that is not the empty string and matches the pattern
179       "/^[a-zA-Z]*[0-9]*\z/", the increment is done as a string, preserving
180       each character within its range, with carry:
181
182           print ++($foo = "99");      # prints "100"
183           print ++($foo = "a0");      # prints "a1"
184           print ++($foo = "Az");      # prints "Ba"
185           print ++($foo = "zz");      # prints "aaa"
186
187       "undef" is always treated as numeric, and in particular is changed to 0
188       before incrementing (so that a post-increment of an undef value will
189       return 0 rather than "undef").
190
191       The auto-decrement operator is not magical.
192
193   Exponentiation
194       Binary "**" is the exponentiation operator.  It binds even more tightly
195       than unary minus, so "-2**4" is "-(2**4)", not "(-2)**4".  (This is
196       implemented using C's pow(3) function, which actually works on doubles
197       internally.)
198
199       Note that certain exponentiation expressions are ill-defined: these
200       include "0**0", "1**Inf", and "Inf**0".  Do not expect any particular
201       results from these special cases, the results are platform-dependent.
202
203   Symbolic Unary Operators
204       Unary "!" performs logical negation, that is, "not".  See also "not"
205       for a lower precedence version of this.
206
207       Unary "-" performs arithmetic negation if the operand is numeric,
208       including any string that looks like a number.  If the operand is an
209       identifier, a string consisting of a minus sign concatenated with the
210       identifier is returned.  Otherwise, if the string starts with a plus or
211       minus, a string starting with the opposite sign is returned.  One
212       effect of these rules is that "-bareword" is equivalent to the string
213       "-bareword".  If, however, the string begins with a non-alphabetic
214       character (excluding "+" or "-"), Perl will attempt to convert the
215       string to a numeric, and the arithmetic negation is performed.  If the
216       string cannot be cleanly converted to a numeric, Perl will give the
217       warning Argument "the string" isn't numeric in negation (-) at ....
218
219       Unary "~" performs bitwise negation, that is, 1's complement.  For
220       example, "0666 & ~027" is 0640.  (See also "Integer Arithmetic" and
221       "Bitwise String Operators".)  Note that the width of the result is
222       platform-dependent: "~0" is 32 bits wide on a 32-bit platform, but 64
223       bits wide on a 64-bit platform, so if you are expecting a certain bit
224       width, remember to use the "&" operator to mask off the excess bits.
225
226       When complementing strings, if all characters have ordinal values under
227       256, then their complements will, also.  But if they do not, all
228       characters will be in either 32- or 64-bit complements, depending on
229       your architecture.  So for example, "~"\x{3B1}"" is "\x{FFFF_FC4E}" on
230       32-bit machines and "\x{FFFF_FFFF_FFFF_FC4E}" on 64-bit machines.
231
232       If the experimental "bitwise" feature is enabled via
233       "use feature 'bitwise'", then unary "~" always treats its argument as a
234       number, and an alternate form of the operator, "~.", always treats its
235       argument as a string.  So "~0" and "~"0"" will both give 2**32-1 on
236       32-bit platforms, whereas "~.0" and "~."0"" will both yield "\xff".
237       This feature produces a warning unless you use
238       "no warnings 'experimental::bitwise'".
239
240       Unary "+" has no effect whatsoever, even on strings.  It is useful
241       syntactically for separating a function name from a parenthesized
242       expression that would otherwise be interpreted as the complete list of
243       function arguments.  (See examples above under "Terms and List
244       Operators (Leftward)".)
245
246       Unary "\" creates a reference to whatever follows it.  See perlreftut
247       and perlref.  Do not confuse this behavior with the behavior of
248       backslash within a string, although both forms do convey the notion of
249       protecting the next thing from interpolation.
250
251   Binding Operators
252       Binary "=~" binds a scalar expression to a pattern match.  Certain
253       operations search or modify the string $_ by default.  This operator
254       makes that kind of operation work on some other string.  The right
255       argument is a search pattern, substitution, or transliteration.  The
256       left argument is what is supposed to be searched, substituted, or
257       transliterated instead of the default $_.  When used in scalar context,
258       the return value generally indicates the success of the operation.  The
259       exceptions are substitution ("s///") and transliteration ("y///") with
260       the "/r" (non-destructive) option, which cause the return value to be
261       the result of the substitution.  Behavior in list context depends on
262       the particular operator.  See "Regexp Quote-Like Operators" for details
263       and perlretut for examples using these operators.
264
265       If the right argument is an expression rather than a search pattern,
266       substitution, or transliteration, it is interpreted as a search pattern
267       at run time.  Note that this means that its contents will be
268       interpolated twice, so
269
270           '\\' =~ q'\\';
271
272       is not ok, as the regex engine will end up trying to compile the
273       pattern "\", which it will consider a syntax error.
274
275       Binary "!~" is just like "=~" except the return value is negated in the
276       logical sense.
277
278       Binary "!~" with a non-destructive substitution ("s///r") or
279       transliteration ("y///r") is a syntax error.
280
281   Multiplicative Operators
282       Binary "*" multiplies two numbers.
283
284       Binary "/" divides two numbers.
285
286       Binary "%" is the modulo operator, which computes the division
287       remainder of its first argument with respect to its second argument.
288       Given integer operands $m and $n: If $n is positive, then "$m % $n" is
289       $m minus the largest multiple of $n less than or equal to $m.  If $n is
290       negative, then "$m % $n" is $m minus the smallest multiple of $n that
291       is not less than $m (that is, the result will be less than or equal to
292       zero).  If the operands $m and $n are floating point values and the
293       absolute value of $n (that is "abs($n)") is less than "(UV_MAX + 1)",
294       only the integer portion of $m and $n will be used in the operation
295       (Note: here "UV_MAX" means the maximum of the unsigned integer type).
296       If the absolute value of the right operand ("abs($n)") is greater than
297       or equal to "(UV_MAX + 1)", "%" computes the floating-point remainder
298       $r in the equation "($r = $m - $i*$n)" where $i is a certain integer
299       that makes $r have the same sign as the right operand $n (not as the
300       left operand $m like C function "fmod()") and the absolute value less
301       than that of $n.  Note that when "use integer" is in scope, "%" gives
302       you direct access to the modulo operator as implemented by your C
303       compiler.  This operator is not as well defined for negative operands,
304       but it will execute faster.
305
306       Binary "x" is the repetition operator.  In scalar context or if the
307       left operand is not enclosed in parentheses, it returns a string
308       consisting of the left operand repeated the number of times specified
309       by the right operand.  In list context, if the left operand is enclosed
310       in parentheses or is a list formed by "qw/STRING/", it repeats the
311       list.  If the right operand is zero or negative (raising a warning on
312       negative), it returns an empty string or an empty list, depending on
313       the context.
314
315           print '-' x 80;             # print row of dashes
316
317           print "\t" x ($tab/8), ' ' x ($tab%8);      # tab over
318
319           @ones = (1) x 80;           # a list of 80 1's
320           @ones = (5) x @ones;        # set all elements to 5
321
322   Additive Operators
323       Binary "+" returns the sum of two numbers.
324
325       Binary "-" returns the difference of two numbers.
326
327       Binary "." concatenates two strings.
328
329   Shift Operators
330       Binary "<<" returns the value of its left argument shifted left by the
331       number of bits specified by the right argument.  Arguments should be
332       integers.  (See also "Integer Arithmetic".)
333
334       Binary ">>" returns the value of its left argument shifted right by the
335       number of bits specified by the right argument.  Arguments should be
336       integers.  (See also "Integer Arithmetic".)
337
338       If "use integer" (see "Integer Arithmetic") is in force then signed C
339       integers are used (arithmetic shift), otherwise unsigned C integers are
340       used (logical shift), even for negative shiftees.  In arithmetic right
341       shift the sign bit is replicated on the left, in logical shift zero
342       bits come in from the left.
343
344       Either way, the implementation isn't going to generate results larger
345       than the size of the integer type Perl was built with (32 bits or 64
346       bits).
347
348       Shifting by negative number of bits means the reverse shift: left shift
349       becomes right shift, right shift becomes left shift.  This is unlike in
350       C, where negative shift is undefined.
351
352       Shifting by more bits than the size of the integers means most of the
353       time zero (all bits fall off), except that under "use integer" right
354       overshifting a negative shiftee results in -1.  This is unlike in C,
355       where shifting by too many bits is undefined.  A common C behavior is
356       "shift by modulo wordbits", so that for example
357
358           1 >> 64 == 1 >> (64 % 64) == 1 >> 0 == 1  # Common C behavior.
359
360       but that is completely accidental.
361
362       If you get tired of being subject to your platform's native integers,
363       the "use bigint" pragma neatly sidesteps the issue altogether:
364
365           print 20 << 20;  # 20971520
366           print 20 << 40;  # 5120 on 32-bit machines,
367                            # 21990232555520 on 64-bit machines
368           use bigint;
369           print 20 << 100; # 25353012004564588029934064107520
370
371   Named Unary Operators
372       The various named unary operators are treated as functions with one
373       argument, with optional parentheses.
374
375       If any list operator ("print()", etc.) or any unary operator
376       ("chdir()", etc.)  is followed by a left parenthesis as the next token,
377       the operator and arguments within parentheses are taken to be of
378       highest precedence, just like a normal function call.  For example,
379       because named unary operators are higher precedence than "||":
380
381           chdir $foo    || die;       # (chdir $foo) || die
382           chdir($foo)   || die;       # (chdir $foo) || die
383           chdir ($foo)  || die;       # (chdir $foo) || die
384           chdir +($foo) || die;       # (chdir $foo) || die
385
386       but, because "*" is higher precedence than named operators:
387
388           chdir $foo * 20;    # chdir ($foo * 20)
389           chdir($foo) * 20;   # (chdir $foo) * 20
390           chdir ($foo) * 20;  # (chdir $foo) * 20
391           chdir +($foo) * 20; # chdir ($foo * 20)
392
393           rand 10 * 20;       # rand (10 * 20)
394           rand(10) * 20;      # (rand 10) * 20
395           rand (10) * 20;     # (rand 10) * 20
396           rand +(10) * 20;    # rand (10 * 20)
397
398       Regarding precedence, the filetest operators, like "-f", "-M", etc. are
399       treated like named unary operators, but they don't follow this
400       functional parenthesis rule.  That means, for example, that
401       "-f($file).".bak"" is equivalent to "-f "$file.bak"".
402
403       See also "Terms and List Operators (Leftward)".
404
405   Relational Operators
406       Perl operators that return true or false generally return values that
407       can be safely used as numbers.  For example, the relational operators
408       in this section and the equality operators in the next one return 1 for
409       true and a special version of the defined empty string, "", which
410       counts as a zero but is exempt from warnings about improper numeric
411       conversions, just as "0 but true" is.
412
413       Binary "<" returns true if the left argument is numerically less than
414       the right argument.
415
416       Binary ">" returns true if the left argument is numerically greater
417       than the right argument.
418
419       Binary "<=" returns true if the left argument is numerically less than
420       or equal to the right argument.
421
422       Binary ">=" returns true if the left argument is numerically greater
423       than or equal to the right argument.
424
425       Binary "lt" returns true if the left argument is stringwise less than
426       the right argument.
427
428       Binary "gt" returns true if the left argument is stringwise greater
429       than the right argument.
430
431       Binary "le" returns true if the left argument is stringwise less than
432       or equal to the right argument.
433
434       Binary "ge" returns true if the left argument is stringwise greater
435       than or equal to the right argument.
436
437   Equality Operators
438       Binary "==" returns true if the left argument is numerically equal to
439       the right argument.
440
441       Binary "!=" returns true if the left argument is numerically not equal
442       to the right argument.
443
444       Binary "<=>" returns -1, 0, or 1 depending on whether the left argument
445       is numerically less than, equal to, or greater than the right argument.
446       If your platform supports "NaN"'s (not-a-numbers) as numeric values,
447       using them with "<=>" returns undef.  "NaN" is not "<", "==", ">", "<="
448       or ">=" anything (even "NaN"), so those 5 return false.  "NaN != NaN"
449       returns true, as does "NaN !=" anything else.  If your platform doesn't
450       support "NaN"'s then "NaN" is just a string with numeric value 0.
451
452           $ perl -le '$x = "NaN"; print "No NaN support here" if $x == $x'
453           $ perl -le '$x = "NaN"; print "NaN support here" if $x != $x'
454
455       (Note that the bigint, bigrat, and bignum pragmas all support "NaN".)
456
457       Binary "eq" returns true if the left argument is stringwise equal to
458       the right argument.
459
460       Binary "ne" returns true if the left argument is stringwise not equal
461       to the right argument.
462
463       Binary "cmp" returns -1, 0, or 1 depending on whether the left argument
464       is stringwise less than, equal to, or greater than the right argument.
465
466       Binary "~~" does a smartmatch between its arguments.  Smart matching is
467       described in the next section.
468
469       "lt", "le", "ge", "gt" and "cmp" use the collation (sort) order
470       specified by the current "LC_COLLATE" locale if a "use locale" form
471       that includes collation is in effect.  See perllocale.  Do not mix
472       these with Unicode, only use them with legacy 8-bit locale encodings.
473       The standard "Unicode::Collate" and "Unicode::Collate::Locale" modules
474       offer much more powerful solutions to collation issues.
475
476       For case-insensitive comparisions, look at the "fc" in perlfunc case-
477       folding function, available in Perl v5.16 or later:
478
479           if ( fc($x) eq fc($y) ) { ... }
480
481   Smartmatch Operator
482       First available in Perl 5.10.1 (the 5.10.0 version behaved
483       differently), binary "~~" does a "smartmatch" between its arguments.
484       This is mostly used implicitly in the "when" construct described in
485       perlsyn, although not all "when" clauses call the smartmatch operator.
486       Unique among all of Perl's operators, the smartmatch operator can
487       recurse.  The smartmatch operator is experimental and its behavior is
488       subject to change.
489
490       It is also unique in that all other Perl operators impose a context
491       (usually string or numeric context) on their operands, autoconverting
492       those operands to those imposed contexts.  In contrast, smartmatch
493       infers contexts from the actual types of its operands and uses that
494       type information to select a suitable comparison mechanism.
495
496       The "~~" operator compares its operands "polymorphically", determining
497       how to compare them according to their actual types (numeric, string,
498       array, hash, etc.)  Like the equality operators with which it shares
499       the same precedence, "~~" returns 1 for true and "" for false.  It is
500       often best read aloud as "in", "inside of", or "is contained in",
501       because the left operand is often looked for inside the right operand.
502       That makes the order of the operands to the smartmatch operand often
503       opposite that of the regular match operator.  In other words, the
504       "smaller" thing is usually placed in the left operand and the larger
505       one in the right.
506
507       The behavior of a smartmatch depends on what type of things its
508       arguments are, as determined by the following table.  The first row of
509       the table whose types apply determines the smartmatch behavior.
510       Because what actually happens is mostly determined by the type of the
511       second operand, the table is sorted on the right operand instead of on
512       the left.
513
514        Left      Right      Description and pseudocode
515        ===============================================================
516        Any       undef      check whether Any is undefined
517                       like: !defined Any
518
519        Any       Object     invoke ~~ overloading on Object, or die
520
521        Right operand is an ARRAY:
522
523        Left      Right      Description and pseudocode
524        ===============================================================
525        ARRAY1    ARRAY2     recurse on paired elements of ARRAY1 and ARRAY2[2]
526                       like: (ARRAY1[0] ~~ ARRAY2[0])
527                               && (ARRAY1[1] ~~ ARRAY2[1]) && ...
528        HASH      ARRAY      any ARRAY elements exist as HASH keys
529                       like: grep { exists HASH->{$_} } ARRAY
530        Regexp    ARRAY      any ARRAY elements pattern match Regexp
531                       like: grep { /Regexp/ } ARRAY
532        undef     ARRAY      undef in ARRAY
533                       like: grep { !defined } ARRAY
534        Any       ARRAY      smartmatch each ARRAY element[3]
535                       like: grep { Any ~~ $_ } ARRAY
536
537        Right operand is a HASH:
538
539        Left      Right      Description and pseudocode
540        ===============================================================
541        HASH1     HASH2      all same keys in both HASHes
542                       like: keys HASH1 ==
543                                grep { exists HASH2->{$_} } keys HASH1
544        ARRAY     HASH       any ARRAY elements exist as HASH keys
545                       like: grep { exists HASH->{$_} } ARRAY
546        Regexp    HASH       any HASH keys pattern match Regexp
547                       like: grep { /Regexp/ } keys HASH
548        undef     HASH       always false (undef can't be a key)
549                       like: 0 == 1
550        Any       HASH       HASH key existence
551                       like: exists HASH->{Any}
552
553        Right operand is CODE:
554
555        Left      Right      Description and pseudocode
556        ===============================================================
557        ARRAY     CODE       sub returns true on all ARRAY elements[1]
558                       like: !grep { !CODE->($_) } ARRAY
559        HASH      CODE       sub returns true on all HASH keys[1]
560                       like: !grep { !CODE->($_) } keys HASH
561        Any       CODE       sub passed Any returns true
562                       like: CODE->(Any)
563
564       Right operand is a Regexp:
565
566        Left      Right      Description and pseudocode
567        ===============================================================
568        ARRAY     Regexp     any ARRAY elements match Regexp
569                       like: grep { /Regexp/ } ARRAY
570        HASH      Regexp     any HASH keys match Regexp
571                       like: grep { /Regexp/ } keys HASH
572        Any       Regexp     pattern match
573                       like: Any =~ /Regexp/
574
575        Other:
576
577        Left      Right      Description and pseudocode
578        ===============================================================
579        Object    Any        invoke ~~ overloading on Object,
580                             or fall back to...
581
582        Any       Num        numeric equality
583                        like: Any == Num
584        Num       nummy[4]    numeric equality
585                        like: Num == nummy
586        undef     Any        check whether undefined
587                        like: !defined(Any)
588        Any       Any        string equality
589                        like: Any eq Any
590
591       Notes:
592
593       1. Empty hashes or arrays match.
594       2. That is, each element smartmatches the element of the same index in
595       the other array.[3]
596       3. If a circular reference is found, fall back to referential equality.
597       4. Either an actual number, or a string that looks like one.
598
599       The smartmatch implicitly dereferences any non-blessed hash or array
600       reference, so the "HASH" and "ARRAY" entries apply in those cases.  For
601       blessed references, the "Object" entries apply.  Smartmatches involving
602       hashes only consider hash keys, never hash values.
603
604       The "like" code entry is not always an exact rendition.  For example,
605       the smartmatch operator short-circuits whenever possible, but "grep"
606       does not.  Also, "grep" in scalar context returns the number of
607       matches, but "~~" returns only true or false.
608
609       Unlike most operators, the smartmatch operator knows to treat "undef"
610       specially:
611
612           use v5.10.1;
613           @array = (1, 2, 3, undef, 4, 5);
614           say "some elements undefined" if undef ~~ @array;
615
616       Each operand is considered in a modified scalar context, the
617       modification being that array and hash variables are passed by
618       reference to the operator, which implicitly dereferences them.  Both
619       elements of each pair are the same:
620
621           use v5.10.1;
622
623           my %hash = (red    => 1, blue   => 2, green  => 3,
624                       orange => 4, yellow => 5, purple => 6,
625                       black  => 7, grey   => 8, white  => 9);
626
627           my @array = qw(red blue green);
628
629           say "some array elements in hash keys" if  @array ~~  %hash;
630           say "some array elements in hash keys" if \@array ~~ \%hash;
631
632           say "red in array" if "red" ~~  @array;
633           say "red in array" if "red" ~~ \@array;
634
635           say "some keys end in e" if /e$/ ~~  %hash;
636           say "some keys end in e" if /e$/ ~~ \%hash;
637
638       Two arrays smartmatch if each element in the first array smartmatches
639       (that is, is "in") the corresponding element in the second array,
640       recursively.
641
642           use v5.10.1;
643           my @little = qw(red blue green);
644           my @bigger = ("red", "blue", [ "orange", "green" ] );
645           if (@little ~~ @bigger) {  # true!
646               say "little is contained in bigger";
647           }
648
649       Because the smartmatch operator recurses on nested arrays, this will
650       still report that "red" is in the array.
651
652           use v5.10.1;
653           my @array = qw(red blue green);
654           my $nested_array = [[[[[[[ @array ]]]]]]];
655           say "red in array" if "red" ~~ $nested_array;
656
657       If two arrays smartmatch each other, then they are deep copies of each
658       others' values, as this example reports:
659
660           use v5.12.0;
661           my @a = (0, 1, 2, [3, [4, 5], 6], 7);
662           my @b = (0, 1, 2, [3, [4, 5], 6], 7);
663
664           if (@a ~~ @b && @b ~~ @a) {
665               say "a and b are deep copies of each other";
666           }
667           elsif (@a ~~ @b) {
668               say "a smartmatches in b";
669           }
670           elsif (@b ~~ @a) {
671               say "b smartmatches in a";
672           }
673           else {
674               say "a and b don't smartmatch each other at all";
675           }
676
677       If you were to set "$b[3] = 4", then instead of reporting that "a and b
678       are deep copies of each other", it now reports that "b smartmatches in
679       a".  That's because the corresponding position in @a contains an array
680       that (eventually) has a 4 in it.
681
682       Smartmatching one hash against another reports whether both contain the
683       same keys, no more and no less.  This could be used to see whether two
684       records have the same field names, without caring what values those
685       fields might have.  For example:
686
687           use v5.10.1;
688           sub make_dogtag {
689               state $REQUIRED_FIELDS = { name=>1, rank=>1, serial_num=>1 };
690
691               my ($class, $init_fields) = @_;
692
693               die "Must supply (only) name, rank, and serial number"
694                   unless $init_fields ~~ $REQUIRED_FIELDS;
695
696               ...
697           }
698
699       However, this only does what you mean if $init_fields is indeed a hash
700       reference. The condition "$init_fields ~~ $REQUIRED_FIELDS" also allows
701       the strings "name", "rank", "serial_num" as well as any array reference
702       that contains "name" or "rank" or "serial_num" anywhere to pass
703       through.
704
705       The smartmatch operator is most often used as the implicit operator of
706       a "when" clause.  See the section on "Switch Statements" in perlsyn.
707
708       Smartmatching of Objects
709
710       To avoid relying on an object's underlying representation, if the
711       smartmatch's right operand is an object that doesn't overload "~~", it
712       raises the exception ""Smartmatching a non-overloaded object breaks
713       encapsulation"".  That's because one has no business digging around to
714       see whether something is "in" an object.  These are all illegal on
715       objects without a "~~" overload:
716
717           %hash ~~ $object
718              42 ~~ $object
719          "fred" ~~ $object
720
721       However, you can change the way an object is smartmatched by
722       overloading the "~~" operator.  This is allowed to extend the usual
723       smartmatch semantics.  For objects that do have an "~~" overload, see
724       overload.
725
726       Using an object as the left operand is allowed, although not very
727       useful.  Smartmatching rules take precedence over overloading, so even
728       if the object in the left operand has smartmatch overloading, this will
729       be ignored.  A left operand that is a non-overloaded object falls back
730       on a string or numeric comparison of whatever the "ref" operator
731       returns.  That means that
732
733           $object ~~ X
734
735       does not invoke the overload method with "X" as an argument.  Instead
736       the above table is consulted as normal, and based on the type of "X",
737       overloading may or may not be invoked.  For simple strings or numbers,
738       "in" becomes equivalent to this:
739
740           $object ~~ $number          ref($object) == $number
741           $object ~~ $string          ref($object) eq $string
742
743       For example, this reports that the handle smells IOish (but please
744       don't really do this!):
745
746           use IO::Handle;
747           my $fh = IO::Handle->new();
748           if ($fh ~~ /\bIO\b/) {
749               say "handle smells IOish";
750           }
751
752       That's because it treats $fh as a string like
753       "IO::Handle=GLOB(0x8039e0)", then pattern matches against that.
754
755   Bitwise And
756       Binary "&" returns its operands ANDed together bit by bit.  Although no
757       warning is currently raised, the result is not well defined when this
758       operation is performed on operands that aren't either numbers (see
759       "Integer Arithmetic") nor bitstrings (see "Bitwise String Operators").
760
761       Note that "&" has lower priority than relational operators, so for
762       example the parentheses are essential in a test like
763
764           print "Even\n" if ($x & 1) == 0;
765
766       If the experimental "bitwise" feature is enabled via
767       "use feature 'bitwise'", then this operator always treats its operand
768       as numbers.  This feature produces a warning unless you also use
769       "no warnings 'experimental::bitwise'".
770
771   Bitwise Or and Exclusive Or
772       Binary "|" returns its operands ORed together bit by bit.
773
774       Binary "^" returns its operands XORed together bit by bit.
775
776       Although no warning is currently raised, the results are not well
777       defined when these operations are performed on operands that aren't
778       either numbers (see "Integer Arithmetic") nor bitstrings (see "Bitwise
779       String Operators").
780
781       Note that "|" and "^" have lower priority than relational operators, so
782       for example the parentheses are essential in a test like
783
784           print "false\n" if (8 | 2) != 10;
785
786       If the experimental "bitwise" feature is enabled via
787       "use feature 'bitwise'", then this operator always treats its operand
788       as numbers.  This feature produces a warning unless you also use
789       "no warnings 'experimental::bitwise'".
790
791   C-style Logical And
792       Binary "&&" performs a short-circuit logical AND operation.  That is,
793       if the left operand is false, the right operand is not even evaluated.
794       Scalar or list context propagates down to the right operand if it is
795       evaluated.
796
797   C-style Logical Or
798       Binary "||" performs a short-circuit logical OR operation.  That is, if
799       the left operand is true, the right operand is not even evaluated.
800       Scalar or list context propagates down to the right operand if it is
801       evaluated.
802
803   Logical Defined-Or
804       Although it has no direct equivalent in C, Perl's "//" operator is
805       related to its C-style "or".  In fact, it's exactly the same as "||",
806       except that it tests the left hand side's definedness instead of its
807       truth.  Thus, "EXPR1 // EXPR2" returns the value of "EXPR1" if it's
808       defined, otherwise, the value of "EXPR2" is returned.  ("EXPR1" is
809       evaluated in scalar context, "EXPR2" in the context of "//" itself).
810       Usually, this is the same result as "defined(EXPR1) ? EXPR1 : EXPR2"
811       (except that the ternary-operator form can be used as a lvalue, while
812       "EXPR1 // EXPR2" cannot).  This is very useful for providing default
813       values for variables.  If you actually want to test if at least one of
814       $x and $y is defined, use "defined($x // $y)".
815
816       The "||", "//" and "&&" operators return the last value evaluated
817       (unlike C's "||" and "&&", which return 0 or 1).  Thus, a reasonably
818       portable way to find out the home directory might be:
819
820           $home =  $ENV{HOME}
821                 // $ENV{LOGDIR}
822                 // (getpwuid($<))[7]
823                 // die "You're homeless!\n";
824
825       In particular, this means that you shouldn't use this for selecting
826       between two aggregates for assignment:
827
828           @a = @b || @c;            # This doesn't do the right thing
829           @a = scalar(@b) || @c;    # because it really means this.
830           @a = @b ? @b : @c;        # This works fine, though.
831
832       As alternatives to "&&" and "||" when used for control flow, Perl
833       provides the "and" and "or" operators (see below).  The short-circuit
834       behavior is identical.  The precedence of "and" and "or" is much lower,
835       however, so that you can safely use them after a list operator without
836       the need for parentheses:
837
838           unlink "alpha", "beta", "gamma"
839                   or gripe(), next LINE;
840
841       With the C-style operators that would have been written like this:
842
843           unlink("alpha", "beta", "gamma")
844                   || (gripe(), next LINE);
845
846       It would be even more readable to write that this way:
847
848           unless(unlink("alpha", "beta", "gamma")) {
849               gripe();
850               next LINE;
851           }
852
853       Using "or" for assignment is unlikely to do what you want; see below.
854
855   Range Operators
856       Binary ".." is the range operator, which is really two different
857       operators depending on the context.  In list context, it returns a list
858       of values counting (up by ones) from the left value to the right value.
859       If the left value is greater than the right value then it returns the
860       empty list.  The range operator is useful for writing "foreach (1..10)"
861       loops and for doing slice operations on arrays.  In the current
862       implementation, no temporary array is created when the range operator
863       is used as the expression in "foreach" loops, but older versions of
864       Perl might burn a lot of memory when you write something like this:
865
866           for (1 .. 1_000_000) {
867               # code
868           }
869
870       The range operator also works on strings, using the magical auto-
871       increment, see below.
872
873       In scalar context, ".." returns a boolean value.  The operator is
874       bistable, like a flip-flop, and emulates the line-range (comma)
875       operator of sed, awk, and various editors.  Each ".." operator
876       maintains its own boolean state, even across calls to a subroutine that
877       contains it.  It is false as long as its left operand is false.  Once
878       the left operand is true, the range operator stays true until the right
879       operand is true, AFTER which the range operator becomes false again.
880       It doesn't become false till the next time the range operator is
881       evaluated.  It can test the right operand and become false on the same
882       evaluation it became true (as in awk), but it still returns true once.
883       If you don't want it to test the right operand until the next
884       evaluation, as in sed, just use three dots ("...") instead of two.  In
885       all other regards, "..." behaves just like ".." does.
886
887       The right operand is not evaluated while the operator is in the "false"
888       state, and the left operand is not evaluated while the operator is in
889       the "true" state.  The precedence is a little lower than || and &&.
890       The value returned is either the empty string for false, or a sequence
891       number (beginning with 1) for true.  The sequence number is reset for
892       each range encountered.  The final sequence number in a range has the
893       string "E0" appended to it, which doesn't affect its numeric value, but
894       gives you something to search for if you want to exclude the endpoint.
895       You can exclude the beginning point by waiting for the sequence number
896       to be greater than 1.
897
898       If either operand of scalar ".." is a constant expression, that operand
899       is considered true if it is equal ("==") to the current input line
900       number (the $. variable).
901
902       To be pedantic, the comparison is actually "int(EXPR) == int(EXPR)",
903       but that is only an issue if you use a floating point expression; when
904       implicitly using $. as described in the previous paragraph, the
905       comparison is "int(EXPR) == int($.)" which is only an issue when $.  is
906       set to a floating point value and you are not reading from a file.
907       Furthermore, "span" .. "spat" or "2.18 .. 3.14" will not do what you
908       want in scalar context because each of the operands are evaluated using
909       their integer representation.
910
911       Examples:
912
913       As a scalar operator:
914
915           if (101 .. 200) { print; } # print 2nd hundred lines, short for
916                                      #  if ($. == 101 .. $. == 200) { print; }
917
918           next LINE if (1 .. /^$/);  # skip header lines, short for
919                                      #   next LINE if ($. == 1 .. /^$/);
920                                      # (typically in a loop labeled LINE)
921
922           s/^/> / if (/^$/ .. eof());  # quote body
923
924           # parse mail messages
925           while (<>) {
926               $in_header =   1  .. /^$/;
927               $in_body   = /^$/ .. eof;
928               if ($in_header) {
929                   # do something
930               } else { # in body
931                   # do something else
932               }
933           } continue {
934               close ARGV if eof;             # reset $. each file
935           }
936
937       Here's a simple example to illustrate the difference between the two
938       range operators:
939
940           @lines = ("   - Foo",
941                     "01 - Bar",
942                     "1  - Baz",
943                     "   - Quux");
944
945           foreach (@lines) {
946               if (/0/ .. /1/) {
947                   print "$_\n";
948               }
949           }
950
951       This program will print only the line containing "Bar".  If the range
952       operator is changed to "...", it will also print the "Baz" line.
953
954       And now some examples as a list operator:
955
956           for (101 .. 200) { print }      # print $_ 100 times
957           @foo = @foo[0 .. $#foo];        # an expensive no-op
958           @foo = @foo[$#foo-4 .. $#foo];  # slice last 5 items
959
960       The range operator (in list context) makes use of the magical auto-
961       increment algorithm if the operands are strings.  You can say
962
963           @alphabet = ("A" .. "Z");
964
965       to get all normal letters of the English alphabet, or
966
967           $hexdigit = (0 .. 9, "a" .. "f")[$num & 15];
968
969       to get a hexadecimal digit, or
970
971           @z2 = ("01" .. "31");
972           print $z2[$mday];
973
974       to get dates with leading zeros.
975
976       If the final value specified is not in the sequence that the magical
977       increment would produce, the sequence goes until the next value would
978       be longer than the final value specified.
979
980       As of Perl 5.26, the list-context range operator on strings works as
981       expected in the scope of "use feature 'unicode_strings". In previous
982       versions, and outside the scope of that feature, it exhibits "The
983       "Unicode Bug"" in perlunicode: its behavior depends on the internal
984       encoding of the range endpoint.
985
986       If the initial value specified isn't part of a magical increment
987       sequence (that is, a non-empty string matching "/^[a-zA-Z]*[0-9]*\z/"),
988       only the initial value will be returned.  So the following will only
989       return an alpha:
990
991           use charnames "greek";
992           my @greek_small =  ("\N{alpha}" .. "\N{omega}");
993
994       To get the 25 traditional lowercase Greek letters, including both
995       sigmas, you could use this instead:
996
997           use charnames "greek";
998           my @greek_small =  map { chr } ( ord("\N{alpha}")
999                                               ..
1000                                            ord("\N{omega}")
1001                                          );
1002
1003       However, because there are many other lowercase Greek characters than
1004       just those, to match lowercase Greek characters in a regular
1005       expression, you could use the pattern "/(?:(?=\p{Greek})\p{Lower})+/"
1006       (or the experimental feature "/(?[ \p{Greek} & \p{Lower} ])+/").
1007
1008       Because each operand is evaluated in integer form, "2.18 .. 3.14" will
1009       return two elements in list context.
1010
1011           @list = (2.18 .. 3.14); # same as @list = (2 .. 3);
1012
1013   Conditional Operator
1014       Ternary "?:" is the conditional operator, just as in C.  It works much
1015       like an if-then-else.  If the argument before the "?" is true, the
1016       argument before the ":" is returned, otherwise the argument after the
1017       ":" is returned.  For example:
1018
1019           printf "I have %d dog%s.\n", $n,
1020                   ($n == 1) ? "" : "s";
1021
1022       Scalar or list context propagates downward into the 2nd or 3rd
1023       argument, whichever is selected.
1024
1025           $x = $ok ? $y : $z;  # get a scalar
1026           @x = $ok ? @y : @z;  # get an array
1027           $x = $ok ? @y : @z;  # oops, that's just a count!
1028
1029       The operator may be assigned to if both the 2nd and 3rd arguments are
1030       legal lvalues (meaning that you can assign to them):
1031
1032           ($x_or_y ? $x : $y) = $z;
1033
1034       Because this operator produces an assignable result, using assignments
1035       without parentheses will get you in trouble.  For example, this:
1036
1037           $x % 2 ? $x += 10 : $x += 2
1038
1039       Really means this:
1040
1041           (($x % 2) ? ($x += 10) : $x) += 2
1042
1043       Rather than this:
1044
1045           ($x % 2) ? ($x += 10) : ($x += 2)
1046
1047       That should probably be written more simply as:
1048
1049           $x += ($x % 2) ? 10 : 2;
1050
1051   Assignment Operators
1052       "=" is the ordinary assignment operator.
1053
1054       Assignment operators work as in C.  That is,
1055
1056           $x += 2;
1057
1058       is equivalent to
1059
1060           $x = $x + 2;
1061
1062       although without duplicating any side effects that dereferencing the
1063       lvalue might trigger, such as from "tie()".  Other assignment operators
1064       work similarly.  The following are recognized:
1065
1066           **=    +=    *=    &=    &.=    <<=    &&=
1067                  -=    /=    |=    |.=    >>=    ||=
1068                  .=    %=    ^=    ^.=           //=
1069                        x=
1070
1071       Although these are grouped by family, they all have the precedence of
1072       assignment.  These combined assignment operators can only operate on
1073       scalars, whereas the ordinary assignment operator can assign to arrays,
1074       hashes, lists and even references.  (See "Context" and "List value
1075       constructors" in perldata, and "Assigning to References" in perlref.)
1076
1077       Unlike in C, the scalar assignment operator produces a valid lvalue.
1078       Modifying an assignment is equivalent to doing the assignment and then
1079       modifying the variable that was assigned to.  This is useful for
1080       modifying a copy of something, like this:
1081
1082           ($tmp = $global) =~ tr/13579/24680/;
1083
1084       Although as of 5.14, that can be also be accomplished this way:
1085
1086           use v5.14;
1087           $tmp = ($global =~  tr/13579/24680/r);
1088
1089       Likewise,
1090
1091           ($x += 2) *= 3;
1092
1093       is equivalent to
1094
1095           $x += 2;
1096           $x *= 3;
1097
1098       Similarly, a list assignment in list context produces the list of
1099       lvalues assigned to, and a list assignment in scalar context returns
1100       the number of elements produced by the expression on the right hand
1101       side of the assignment.
1102
1103       The three dotted bitwise assignment operators ("&.=" "|.=" "^.=") are
1104       new in Perl 5.22 and experimental.  See "Bitwise String Operators".
1105
1106   Comma Operator
1107       Binary "," is the comma operator.  In scalar context it evaluates its
1108       left argument, throws that value away, then evaluates its right
1109       argument and returns that value.  This is just like C's comma operator.
1110
1111       In list context, it's just the list argument separator, and inserts
1112       both its arguments into the list.  These arguments are also evaluated
1113       from left to right.
1114
1115       The "=>" operator (sometimes pronounced "fat comma") is a synonym for
1116       the comma except that it causes a word on its left to be interpreted as
1117       a string if it begins with a letter or underscore and is composed only
1118       of letters, digits and underscores.  This includes operands that might
1119       otherwise be interpreted as operators, constants, single number
1120       v-strings or function calls.  If in doubt about this behavior, the left
1121       operand can be quoted explicitly.
1122
1123       Otherwise, the "=>" operator behaves exactly as the comma operator or
1124       list argument separator, according to context.
1125
1126       For example:
1127
1128           use constant FOO => "something";
1129
1130           my %h = ( FOO => 23 );
1131
1132       is equivalent to:
1133
1134           my %h = ("FOO", 23);
1135
1136       It is NOT:
1137
1138           my %h = ("something", 23);
1139
1140       The "=>" operator is helpful in documenting the correspondence between
1141       keys and values in hashes, and other paired elements in lists.
1142
1143           %hash = ( $key => $value );
1144           login( $username => $password );
1145
1146       The special quoting behavior ignores precedence, and hence may apply to
1147       part of the left operand:
1148
1149           print time.shift => "bbb";
1150
1151       That example prints something like "1314363215shiftbbb", because the
1152       "=>" implicitly quotes the "shift" immediately on its left, ignoring
1153       the fact that "time.shift" is the entire left operand.
1154
1155   List Operators (Rightward)
1156       On the right side of a list operator, the comma has very low
1157       precedence, such that it controls all comma-separated expressions found
1158       there.  The only operators with lower precedence are the logical
1159       operators "and", "or", and "not", which may be used to evaluate calls
1160       to list operators without the need for parentheses:
1161
1162           open HANDLE, "< :encoding(UTF-8)", "filename"
1163               or die "Can't open: $!\n";
1164
1165       However, some people find that code harder to read than writing it with
1166       parentheses:
1167
1168           open(HANDLE, "< :encoding(UTF-8)", "filename")
1169               or die "Can't open: $!\n";
1170
1171       in which case you might as well just use the more customary "||"
1172       operator:
1173
1174           open(HANDLE, "< :encoding(UTF-8)", "filename")
1175               || die "Can't open: $!\n";
1176
1177       See also discussion of list operators in "Terms and List Operators
1178       (Leftward)".
1179
1180   Logical Not
1181       Unary "not" returns the logical negation of the expression to its
1182       right.  It's the equivalent of "!" except for the very low precedence.
1183
1184   Logical And
1185       Binary "and" returns the logical conjunction of the two surrounding
1186       expressions.  It's equivalent to "&&" except for the very low
1187       precedence.  This means that it short-circuits: the right expression is
1188       evaluated only if the left expression is true.
1189
1190   Logical or and Exclusive Or
1191       Binary "or" returns the logical disjunction of the two surrounding
1192       expressions.  It's equivalent to "||" except for the very low
1193       precedence.  This makes it useful for control flow:
1194
1195           print FH $data              or die "Can't write to FH: $!";
1196
1197       This means that it short-circuits: the right expression is evaluated
1198       only if the left expression is false.  Due to its precedence, you must
1199       be careful to avoid using it as replacement for the "||" operator.  It
1200       usually works out better for flow control than in assignments:
1201
1202           $x = $y or $z;              # bug: this is wrong
1203           ($x = $y) or $z;            # really means this
1204           $x = $y || $z;              # better written this way
1205
1206       However, when it's a list-context assignment and you're trying to use
1207       "||" for control flow, you probably need "or" so that the assignment
1208       takes higher precedence.
1209
1210           @info = stat($file) || die;     # oops, scalar sense of stat!
1211           @info = stat($file) or die;     # better, now @info gets its due
1212
1213       Then again, you could always use parentheses.
1214
1215       Binary "xor" returns the exclusive-OR of the two surrounding
1216       expressions.  It cannot short-circuit (of course).
1217
1218       There is no low precedence operator for defined-OR.
1219
1220   C Operators Missing From Perl
1221       Here is what C has that Perl doesn't:
1222
1223       unary & Address-of operator.  (But see the "\" operator for taking a
1224               reference.)
1225
1226       unary * Dereference-address operator.  (Perl's prefix dereferencing
1227               operators are typed: "$", "@", "%", and "&".)
1228
1229       (TYPE)  Type-casting operator.
1230
1231   Quote and Quote-like Operators
1232       While we usually think of quotes as literal values, in Perl they
1233       function as operators, providing various kinds of interpolating and
1234       pattern matching capabilities.  Perl provides customary quote
1235       characters for these behaviors, but also provides a way for you to
1236       choose your quote character for any of them.  In the following table, a
1237       "{}" represents any pair of delimiters you choose.
1238
1239           Customary  Generic        Meaning        Interpolates
1240               ''       q{}          Literal             no
1241               ""      qq{}          Literal             yes
1242               ``      qx{}          Command             yes*
1243                       qw{}         Word list            no
1244               //       m{}       Pattern match          yes*
1245                       qr{}          Pattern             yes*
1246                        s{}{}      Substitution          yes*
1247                       tr{}{}    Transliteration         no (but see below)
1248                        y{}{}    Transliteration         no (but see below)
1249               <<EOF                 here-doc            yes*
1250
1251               * unless the delimiter is ''.
1252
1253       Non-bracketing delimiters use the same character fore and aft, but the
1254       four sorts of ASCII brackets (round, angle, square, curly) all nest,
1255       which means that
1256
1257           q{foo{bar}baz}
1258
1259       is the same as
1260
1261           'foo{bar}baz'
1262
1263       Note, however, that this does not always work for quoting Perl code:
1264
1265           $s = q{ if($x eq "}") ... }; # WRONG
1266
1267       is a syntax error.  The "Text::Balanced" module (standard as of v5.8,
1268       and from CPAN before then) is able to do this properly.
1269
1270       There can (and in some cases, must) be whitespace between the operator
1271       and the quoting characters, except when "#" is being used as the
1272       quoting character.  "q#foo#" is parsed as the string "foo", while
1273       "q #foo#" is the operator "q" followed by a comment.  Its argument will
1274       be taken from the next line.  This allows you to write:
1275
1276           s {foo}  # Replace foo
1277             {bar}  # with bar.
1278
1279       The cases where whitespace must be used are when the quoting character
1280       is a word character (meaning it matches "/\w/"):
1281
1282           q XfooX # Works: means the string 'foo'
1283           qXfooX  # WRONG!
1284
1285       The following escape sequences are available in constructs that
1286       interpolate, and in transliterations:
1287
1288           Sequence     Note  Description
1289           \t                  tab               (HT, TAB)
1290           \n                  newline           (NL)
1291           \r                  return            (CR)
1292           \f                  form feed         (FF)
1293           \b                  backspace         (BS)
1294           \a                  alarm (bell)      (BEL)
1295           \e                  escape            (ESC)
1296           \x{263A}     [1,8]  hex char          (example: SMILEY)
1297           \x1b         [2,8]  restricted range hex char (example: ESC)
1298           \N{name}     [3]    named Unicode character or character sequence
1299           \N{U+263D}   [4,8]  Unicode character (example: FIRST QUARTER MOON)
1300           \c[          [5]    control char      (example: chr(27))
1301           \o{23072}    [6,8]  octal char        (example: SMILEY)
1302           \033         [7,8]  restricted range octal char  (example: ESC)
1303
1304       [1] The result is the character specified by the hexadecimal number
1305           between the braces.  See "[8]" below for details on which
1306           character.
1307
1308           Only hexadecimal digits are valid between the braces.  If an
1309           invalid character is encountered, a warning will be issued and the
1310           invalid character and all subsequent characters (valid or invalid)
1311           within the braces will be discarded.
1312
1313           If there are no valid digits between the braces, the generated
1314           character is the NULL character ("\x{00}").  However, an explicit
1315           empty brace ("\x{}") will not cause a warning (currently).
1316
1317       [2] The result is the character specified by the hexadecimal number in
1318           the range 0x00 to 0xFF.  See "[8]" below for details on which
1319           character.
1320
1321           Only hexadecimal digits are valid following "\x".  When "\x" is
1322           followed by fewer than two valid digits, any valid digits will be
1323           zero-padded.  This means that "\x7" will be interpreted as "\x07",
1324           and a lone "\x" will be interpreted as "\x00".  Except at the end
1325           of a string, having fewer than two valid digits will result in a
1326           warning.  Note that although the warning says the illegal character
1327           is ignored, it is only ignored as part of the escape and will still
1328           be used as the subsequent character in the string.  For example:
1329
1330             Original    Result    Warns?
1331             "\x7"       "\x07"    no
1332             "\x"        "\x00"    no
1333             "\x7q"      "\x07q"   yes
1334             "\xq"       "\x00q"   yes
1335
1336       [3] The result is the Unicode character or character sequence given by
1337           name.  See charnames.
1338
1339       [4] "\N{U+hexadecimal number}" means the Unicode character whose
1340           Unicode code point is hexadecimal number.
1341
1342       [5] The character following "\c" is mapped to some other character as
1343           shown in the table:
1344
1345            Sequence   Value
1346              \c@      chr(0)
1347              \cA      chr(1)
1348              \ca      chr(1)
1349              \cB      chr(2)
1350              \cb      chr(2)
1351              ...
1352              \cZ      chr(26)
1353              \cz      chr(26)
1354              \c[      chr(27)
1355                                # See below for chr(28)
1356              \c]      chr(29)
1357              \c^      chr(30)
1358              \c_      chr(31)
1359              \c?      chr(127) # (on ASCII platforms; see below for link to
1360                                #  EBCDIC discussion)
1361
1362           In other words, it's the character whose code point has had 64
1363           xor'd with its uppercase.  "\c?" is DELETE on ASCII platforms
1364           because "ord("?") ^ 64" is 127, and "\c@" is NULL because the ord
1365           of "@" is 64, so xor'ing 64 itself produces 0.
1366
1367           Also, "\c\X" yields " chr(28) . "X"" for any X, but cannot come at
1368           the end of a string, because the backslash would be parsed as
1369           escaping the end quote.
1370
1371           On ASCII platforms, the resulting characters from the list above
1372           are the complete set of ASCII controls.  This isn't the case on
1373           EBCDIC platforms; see "OPERATOR DIFFERENCES" in perlebcdic for a
1374           full discussion of the differences between these for ASCII versus
1375           EBCDIC platforms.
1376
1377           Use of any other character following the "c" besides those listed
1378           above is discouraged, and as of Perl v5.20, the only characters
1379           actually allowed are the printable ASCII ones, minus the left brace
1380           "{".  What happens for any of the allowed other characters is that
1381           the value is derived by xor'ing with the seventh bit, which is 64,
1382           and a warning raised if enabled.  Using the non-allowed characters
1383           generates a fatal error.
1384
1385           To get platform independent controls, you can use "\N{...}".
1386
1387       [6] The result is the character specified by the octal number between
1388           the braces.  See "[8]" below for details on which character.
1389
1390           If a character that isn't an octal digit is encountered, a warning
1391           is raised, and the value is based on the octal digits before it,
1392           discarding it and all following characters up to the closing brace.
1393           It is a fatal error if there are no octal digits at all.
1394
1395       [7] The result is the character specified by the three-digit octal
1396           number in the range 000 to 777 (but best to not use above 077, see
1397           next paragraph).  See "[8]" below for details on which character.
1398
1399           Some contexts allow 2 or even 1 digit, but any usage without
1400           exactly three digits, the first being a zero, may give unintended
1401           results.  (For example, in a regular expression it may be confused
1402           with a backreference; see "Octal escapes" in perlrebackslash.)
1403           Starting in Perl 5.14, you may use "\o{}" instead, which avoids all
1404           these problems.  Otherwise, it is best to use this construct only
1405           for ordinals "\077" and below, remembering to pad to the left with
1406           zeros to make three digits.  For larger ordinals, either use
1407           "\o{}", or convert to something else, such as to hex and use
1408           "\N{U+}" (which is portable between platforms with different
1409           character sets) or "\x{}" instead.
1410
1411       [8] Several constructs above specify a character by a number.  That
1412           number gives the character's position in the character set encoding
1413           (indexed from 0).  This is called synonymously its ordinal, code
1414           position, or code point.  Perl works on platforms that have a
1415           native encoding currently of either ASCII/Latin1 or EBCDIC, each of
1416           which allow specification of 256 characters.  In general, if the
1417           number is 255 (0xFF, 0377) or below, Perl interprets this in the
1418           platform's native encoding.  If the number is 256 (0x100, 0400) or
1419           above, Perl interprets it as a Unicode code point and the result is
1420           the corresponding Unicode character.  For example "\x{50}" and
1421           "\o{120}" both are the number 80 in decimal, which is less than
1422           256, so the number is interpreted in the native character set
1423           encoding.  In ASCII the character in the 80th position (indexed
1424           from 0) is the letter "P", and in EBCDIC it is the ampersand symbol
1425           "&".  "\x{100}" and "\o{400}" are both 256 in decimal, so the
1426           number is interpreted as a Unicode code point no matter what the
1427           native encoding is.  The name of the character in the 256th
1428           position (indexed by 0) in Unicode is "LATIN CAPITAL LETTER A WITH
1429           MACRON".
1430
1431           An exception to the above rule is that "\N{U+hex number}" is always
1432           interpreted as a Unicode code point, so that "\N{U+0050}" is "P"
1433           even on EBCDIC platforms.
1434
1435       NOTE: Unlike C and other languages, Perl has no "\v" escape sequence
1436       for the vertical tab (VT, which is 11 in both ASCII and EBCDIC), but
1437       you may use "\N{VT}", "\ck", "\N{U+0b}", or "\x0b".  ("\v" does have
1438       meaning in regular expression patterns in Perl, see perlre.)
1439
1440       The following escape sequences are available in constructs that
1441       interpolate, but not in transliterations.
1442
1443           \l          lowercase next character only
1444           \u          titlecase (not uppercase!) next character only
1445           \L          lowercase all characters till \E or end of string
1446           \U          uppercase all characters till \E or end of string
1447           \F          foldcase all characters till \E or end of string
1448           \Q          quote (disable) pattern metacharacters till \E or
1449                       end of string
1450           \E          end either case modification or quoted section
1451                       (whichever was last seen)
1452
1453       See "quotemeta" in perlfunc for the exact definition of characters that
1454       are quoted by "\Q".
1455
1456       "\L", "\U", "\F", and "\Q" can stack, in which case you need one "\E"
1457       for each.  For example:
1458
1459        say"This \Qquoting \ubusiness \Uhere isn't quite\E done yet,\E is it?";
1460        This quoting\ Business\ HERE\ ISN\'T\ QUITE\ done\ yet\, is it?
1461
1462       If a "use locale" form that includes "LC_CTYPE" is in effect (see
1463       perllocale), the case map used by "\l", "\L", "\u", and "\U" is taken
1464       from the current locale.  If Unicode (for example, "\N{}" or code
1465       points of 0x100 or beyond) is being used, the case map used by "\l",
1466       "\L", "\u", and "\U" is as defined by Unicode.  That means that case-
1467       mapping a single character can sometimes produce a sequence of several
1468       characters.  Under "use locale", "\F" produces the same results as "\L"
1469       for all locales but a UTF-8 one, where it instead uses the Unicode
1470       definition.
1471
1472       All systems use the virtual "\n" to represent a line terminator, called
1473       a "newline".  There is no such thing as an unvarying, physical newline
1474       character.  It is only an illusion that the operating system, device
1475       drivers, C libraries, and Perl all conspire to preserve.  Not all
1476       systems read "\r" as ASCII CR and "\n" as ASCII LF.  For example, on
1477       the ancient Macs (pre-MacOS X) of yesteryear, these used to be
1478       reversed, and on systems without a line terminator, printing "\n" might
1479       emit no actual data.  In general, use "\n" when you mean a "newline"
1480       for your system, but use the literal ASCII when you need an exact
1481       character.  For example, most networking protocols expect and prefer a
1482       CR+LF ("\015\012" or "\cM\cJ") for line terminators, and although they
1483       often accept just "\012", they seldom tolerate just "\015".  If you get
1484       in the habit of using "\n" for networking, you may be burned some day.
1485
1486       For constructs that do interpolate, variables beginning with ""$"" or
1487       ""@"" are interpolated.  Subscripted variables such as $a[3] or
1488       "$href->{key}[0]" are also interpolated, as are array and hash slices.
1489       But method calls such as "$obj->meth" are not.
1490
1491       Interpolating an array or slice interpolates the elements in order,
1492       separated by the value of $", so is equivalent to interpolating
1493       "join $", @array".  "Punctuation" arrays such as "@*" are usually
1494       interpolated only if the name is enclosed in braces "@{*}", but the
1495       arrays @_, "@+", and "@-" are interpolated even without braces.
1496
1497       For double-quoted strings, the quoting from "\Q" is applied after
1498       interpolation and escapes are processed.
1499
1500           "abc\Qfoo\tbar$s\Exyz"
1501
1502       is equivalent to
1503
1504           "abc" . quotemeta("foo\tbar$s") . "xyz"
1505
1506       For the pattern of regex operators ("qr//", "m//" and "s///"), the
1507       quoting from "\Q" is applied after interpolation is processed, but
1508       before escapes are processed.  This allows the pattern to match
1509       literally (except for "$" and "@").  For example, the following
1510       matches:
1511
1512           '\s\t' =~ /\Q\s\t/
1513
1514       Because "$" or "@" trigger interpolation, you'll need to use something
1515       like "/\Quser\E\@\Qhost/" to match them literally.
1516
1517       Patterns are subject to an additional level of interpretation as a
1518       regular expression.  This is done as a second pass, after variables are
1519       interpolated, so that regular expressions may be incorporated into the
1520       pattern from the variables.  If this is not what you want, use "\Q" to
1521       interpolate a variable literally.
1522
1523       Apart from the behavior described above, Perl does not expand multiple
1524       levels of interpolation.  In particular, contrary to the expectations
1525       of shell programmers, back-quotes do NOT interpolate within double
1526       quotes, nor do single quotes impede evaluation of variables when used
1527       within double quotes.
1528
1529   Regexp Quote-Like Operators
1530       Here are the quote-like operators that apply to pattern matching and
1531       related activities.
1532
1533       "qr/STRING/msixpodualn"
1534               This operator quotes (and possibly compiles) its STRING as a
1535               regular expression.  STRING is interpolated the same way as
1536               PATTERN in "m/PATTERN/".  If "'" is used as the delimiter, no
1537               variable interpolation is done.  Returns a Perl value which may
1538               be used instead of the corresponding "/STRING/msixpodualn"
1539               expression.  The returned value is a normalized version of the
1540               original pattern.  It magically differs from a string
1541               containing the same characters: "ref(qr/x/)" returns "Regexp";
1542               however, dereferencing it is not well defined (you currently
1543               get the normalized version of the original pattern, but this
1544               may change).
1545
1546               For example,
1547
1548                   $rex = qr/my.STRING/is;
1549                   print $rex;                 # prints (?si-xm:my.STRING)
1550                   s/$rex/foo/;
1551
1552               is equivalent to
1553
1554                   s/my.STRING/foo/is;
1555
1556               The result may be used as a subpattern in a match:
1557
1558                   $re = qr/$pattern/;
1559                   $string =~ /foo${re}bar/;   # can be interpolated in other
1560                                               # patterns
1561                   $string =~ $re;             # or used standalone
1562                   $string =~ /$re/;           # or this way
1563
1564               Since Perl may compile the pattern at the moment of execution
1565               of the "qr()" operator, using "qr()" may have speed advantages
1566               in some situations, notably if the result of "qr()" is used
1567               standalone:
1568
1569                   sub match {
1570                       my $patterns = shift;
1571                       my @compiled = map qr/$_/i, @$patterns;
1572                       grep {
1573                           my $success = 0;
1574                           foreach my $pat (@compiled) {
1575                               $success = 1, last if /$pat/;
1576                           }
1577                           $success;
1578                       } @_;
1579                   }
1580
1581               Precompilation of the pattern into an internal representation
1582               at the moment of "qr()" avoids the need to recompile the
1583               pattern every time a match "/$pat/" is attempted.  (Perl has
1584               many other internal optimizations, but none would be triggered
1585               in the above example if we did not use "qr()" operator.)
1586
1587               Options (specified by the following modifiers) are:
1588
1589                   m   Treat string as multiple lines.
1590                   s   Treat string as single line. (Make . match a newline)
1591                   i   Do case-insensitive pattern matching.
1592                   x   Use extended regular expressions; specifying two
1593                       x's means \t and the SPACE character are ignored within
1594                       square-bracketed character classes
1595                   p   When matching preserve a copy of the matched string so
1596                       that ${^PREMATCH}, ${^MATCH}, ${^POSTMATCH} will be
1597                       defined (ignored starting in v5.20) as these are always
1598                       defined starting in that release
1599                   o   Compile pattern only once.
1600                   a   ASCII-restrict: Use ASCII for \d, \s, \w and [[:posix:]]
1601                       character classes; specifying two a's adds the further
1602                       restriction that no ASCII character will match a
1603                       non-ASCII one under /i.
1604                   l   Use the current run-time locale's rules.
1605                   u   Use Unicode rules.
1606                   d   Use Unicode or native charset, as in 5.12 and earlier.
1607                   n   Non-capture mode. Don't let () fill in $1, $2, etc...
1608
1609               If a precompiled pattern is embedded in a larger pattern then
1610               the effect of "msixpluadn" will be propagated appropriately.
1611               The effect that the "/o" modifier has is not propagated, being
1612               restricted to those patterns explicitly using it.
1613
1614               The last four modifiers listed above, added in Perl 5.14,
1615               control the character set rules, but "/a" is the only one you
1616               are likely to want to specify explicitly; the other three are
1617               selected automatically by various pragmas.
1618
1619               See perlre for additional information on valid syntax for
1620               STRING, and for a detailed look at the semantics of regular
1621               expressions.  In particular, all modifiers except the largely
1622               obsolete "/o" are further explained in "Modifiers" in perlre.
1623               "/o" is described in the next section.
1624
1625       "m/PATTERN/msixpodualngc"
1626       "/PATTERN/msixpodualngc"
1627               Searches a string for a pattern match, and in scalar context
1628               returns true if it succeeds, false if it fails.  If no string
1629               is specified via the "=~" or "!~" operator, the $_ string is
1630               searched.  (The string specified with "=~" need not be an
1631               lvalue--it may be the result of an expression evaluation, but
1632               remember the "=~" binds rather tightly.)  See also perlre.
1633
1634               Options are as described in "qr//" above; in addition, the
1635               following match process modifiers are available:
1636
1637                g  Match globally, i.e., find all occurrences.
1638                c  Do not reset search position on a failed match when /g is
1639                   in effect.
1640
1641               If "/" is the delimiter then the initial "m" is optional.  With
1642               the "m" you can use any pair of non-whitespace (ASCII)
1643               characters as delimiters.  This is particularly useful for
1644               matching path names that contain "/", to avoid LTS (leaning
1645               toothpick syndrome).  If "?" is the delimiter, then a match-
1646               only-once rule applies, described in "m?PATTERN?" below.  If
1647               "'" (single quote) is the delimiter, no variable interpolation
1648               is performed on the PATTERN.  When using a delimiter character
1649               valid in an identifier, whitespace is required after the "m".
1650
1651               PATTERN may contain variables, which will be interpolated every
1652               time the pattern search is evaluated, except for when the
1653               delimiter is a single quote.  (Note that $(, $), and $| are not
1654               interpolated because they look like end-of-string tests.)  Perl
1655               will not recompile the pattern unless an interpolated variable
1656               that it contains changes.  You can force Perl to skip the test
1657               and never recompile by adding a "/o" (which stands for "once")
1658               after the trailing delimiter.  Once upon a time, Perl would
1659               recompile regular expressions unnecessarily, and this modifier
1660               was useful to tell it not to do so, in the interests of speed.
1661               But now, the only reasons to use "/o" are one of:
1662
1663               1.  The variables are thousands of characters long and you know
1664                   that they don't change, and you need to wring out the last
1665                   little bit of speed by having Perl skip testing for that.
1666                   (There is a maintenance penalty for doing this, as
1667                   mentioning "/o" constitutes a promise that you won't change
1668                   the variables in the pattern.  If you do change them, Perl
1669                   won't even notice.)
1670
1671               2.  you want the pattern to use the initial values of the
1672                   variables regardless of whether they change or not.  (But
1673                   there are saner ways of accomplishing this than using
1674                   "/o".)
1675
1676               3.  If the pattern contains embedded code, such as
1677
1678                       use re 'eval';
1679                       $code = 'foo(?{ $x })';
1680                       /$code/
1681
1682                   then perl will recompile each time, even though the pattern
1683                   string hasn't changed, to ensure that the current value of
1684                   $x is seen each time.  Use "/o" if you want to avoid this.
1685
1686               The bottom line is that using "/o" is almost never a good idea.
1687
1688       The empty pattern "//"
1689               If the PATTERN evaluates to the empty string, the last
1690               successfully matched regular expression is used instead.  In
1691               this case, only the "g" and "c" flags on the empty pattern are
1692               honored; the other flags are taken from the original pattern.
1693               If no match has previously succeeded, this will (silently) act
1694               instead as a genuine empty pattern (which will always match).
1695
1696               Note that it's possible to confuse Perl into thinking "//" (the
1697               empty regex) is really "//" (the defined-or operator).  Perl is
1698               usually pretty good about this, but some pathological cases
1699               might trigger this, such as "$x///" (is that "($x) / (//)" or
1700               "$x // /"?) and "print $fh //" ("print $fh(//" or
1701               "print($fh //"?).  In all of these examples, Perl will assume
1702               you meant defined-or.  If you meant the empty regex, just use
1703               parentheses or spaces to disambiguate, or even prefix the empty
1704               regex with an "m" (so "//" becomes "m//").
1705
1706       Matching in list context
1707               If the "/g" option is not used, "m//" in list context returns a
1708               list consisting of the subexpressions matched by the
1709               parentheses in the pattern, that is, ($1, $2, $3...)  (Note
1710               that here $1 etc. are also set).  When there are no parentheses
1711               in the pattern, the return value is the list "(1)" for success.
1712               With or without parentheses, an empty list is returned upon
1713               failure.
1714
1715               Examples:
1716
1717                open(TTY, "+</dev/tty")
1718                   || die "can't access /dev/tty: $!";
1719
1720                <TTY> =~ /^y/i && foo();       # do foo if desired
1721
1722                if (/Version: *([0-9.]*)/) { $version = $1; }
1723
1724                next if m#^/usr/spool/uucp#;
1725
1726                # poor man's grep
1727                $arg = shift;
1728                while (<>) {
1729                   print if /$arg/o; # compile only once (no longer needed!)
1730                }
1731
1732                if (($F1, $F2, $Etc) = ($foo =~ /^(\S+)\s+(\S+)\s*(.*)/))
1733
1734               This last example splits $foo into the first two words and the
1735               remainder of the line, and assigns those three fields to $F1,
1736               $F2, and $Etc.  The conditional is true if any variables were
1737               assigned; that is, if the pattern matched.
1738
1739               The "/g" modifier specifies global pattern matching--that is,
1740               matching as many times as possible within the string.  How it
1741               behaves depends on the context.  In list context, it returns a
1742               list of the substrings matched by any capturing parentheses in
1743               the regular expression.  If there are no parentheses, it
1744               returns a list of all the matched strings, as if there were
1745               parentheses around the whole pattern.
1746
1747               In scalar context, each execution of "m//g" finds the next
1748               match, returning true if it matches, and false if there is no
1749               further match.  The position after the last match can be read
1750               or set using the "pos()" function; see "pos" in perlfunc.  A
1751               failed match normally resets the search position to the
1752               beginning of the string, but you can avoid that by adding the
1753               "/c" modifier (for example, "m//gc").  Modifying the target
1754               string also resets the search position.
1755
1756       "\G assertion"
1757               You can intermix "m//g" matches with "m/\G.../g", where "\G" is
1758               a zero-width assertion that matches the exact position where
1759               the previous "m//g", if any, left off.  Without the "/g"
1760               modifier, the "\G" assertion still anchors at "pos()" as it was
1761               at the start of the operation (see "pos" in perlfunc), but the
1762               match is of course only attempted once.  Using "\G" without
1763               "/g" on a target string that has not previously had a "/g"
1764               match applied to it is the same as using the "\A" assertion to
1765               match the beginning of the string.  Note also that, currently,
1766               "\G" is only properly supported when anchored at the very
1767               beginning of the pattern.
1768
1769               Examples:
1770
1771                   # list context
1772                   ($one,$five,$fifteen) = (`uptime` =~ /(\d+\.\d+)/g);
1773
1774                   # scalar context
1775                   local $/ = "";
1776                   while ($paragraph = <>) {
1777                       while ($paragraph =~ /\p{Ll}['")]*[.!?]+['")]*\s/g) {
1778                           $sentences++;
1779                       }
1780                   }
1781                   say $sentences;
1782
1783               Here's another way to check for sentences in a paragraph:
1784
1785                my $sentence_rx = qr{
1786                   (?: (?<= ^ ) | (?<= \s ) )  # after start-of-string or
1787                                               # whitespace
1788                   \p{Lu}                      # capital letter
1789                   .*?                         # a bunch of anything
1790                   (?<= \S )                   # that ends in non-
1791                                               # whitespace
1792                   (?<! \b [DMS]r  )           # but isn't a common abbr.
1793                   (?<! \b Mrs )
1794                   (?<! \b Sra )
1795                   (?<! \b St  )
1796                   [.?!]                       # followed by a sentence
1797                                               # ender
1798                   (?= $ | \s )                # in front of end-of-string
1799                                               # or whitespace
1800                }sx;
1801                local $/ = "";
1802                while (my $paragraph = <>) {
1803                   say "NEW PARAGRAPH";
1804                   my $count = 0;
1805                   while ($paragraph =~ /($sentence_rx)/g) {
1806                       printf "\tgot sentence %d: <%s>\n", ++$count, $1;
1807                   }
1808                }
1809
1810               Here's how to use "m//gc" with "\G":
1811
1812                   $_ = "ppooqppqq";
1813                   while ($i++ < 2) {
1814                       print "1: '";
1815                       print $1 while /(o)/gc; print "', pos=", pos, "\n";
1816                       print "2: '";
1817                       print $1 if /\G(q)/gc;  print "', pos=", pos, "\n";
1818                       print "3: '";
1819                       print $1 while /(p)/gc; print "', pos=", pos, "\n";
1820                   }
1821                   print "Final: '$1', pos=",pos,"\n" if /\G(.)/;
1822
1823               The last example should print:
1824
1825                   1: 'oo', pos=4
1826                   2: 'q', pos=5
1827                   3: 'pp', pos=7
1828                   1: '', pos=7
1829                   2: 'q', pos=8
1830                   3: '', pos=8
1831                   Final: 'q', pos=8
1832
1833               Notice that the final match matched "q" instead of "p", which a
1834               match without the "\G" anchor would have done.  Also note that
1835               the final match did not update "pos".  "pos" is only updated on
1836               a "/g" match.  If the final match did indeed match "p", it's a
1837               good bet that you're running a very old (pre-5.6.0) version of
1838               Perl.
1839
1840               A useful idiom for "lex"-like scanners is "/\G.../gc".  You can
1841               combine several regexps like this to process a string part-by-
1842               part, doing different actions depending on which regexp
1843               matched.  Each regexp tries to match where the previous one
1844               leaves off.
1845
1846                $_ = <<'EOL';
1847                   $url = URI::URL->new( "http://example.com/" );
1848                   die if $url eq "xXx";
1849                EOL
1850
1851                LOOP: {
1852                    print(" digits"),       redo LOOP if /\G\d+\b[,.;]?\s*/gc;
1853                    print(" lowercase"),    redo LOOP
1854                                                   if /\G\p{Ll}+\b[,.;]?\s*/gc;
1855                    print(" UPPERCASE"),    redo LOOP
1856                                                   if /\G\p{Lu}+\b[,.;]?\s*/gc;
1857                    print(" Capitalized"),  redo LOOP
1858                                             if /\G\p{Lu}\p{Ll}+\b[,.;]?\s*/gc;
1859                    print(" MiXeD"),        redo LOOP if /\G\pL+\b[,.;]?\s*/gc;
1860                    print(" alphanumeric"), redo LOOP
1861                                           if /\G[\p{Alpha}\pN]+\b[,.;]?\s*/gc;
1862                    print(" line-noise"),   redo LOOP if /\G\W+/gc;
1863                    print ". That's all!\n";
1864                }
1865
1866               Here is the output (split into several lines):
1867
1868                line-noise lowercase line-noise UPPERCASE line-noise UPPERCASE
1869                line-noise lowercase line-noise lowercase line-noise lowercase
1870                lowercase line-noise lowercase lowercase line-noise lowercase
1871                lowercase line-noise MiXeD line-noise. That's all!
1872
1873       "m?PATTERN?msixpodualngc"
1874               This is just like the "m/PATTERN/" search, except that it
1875               matches only once between calls to the "reset()" operator.
1876               This is a useful optimization when you want to see only the
1877               first occurrence of something in each file of a set of files,
1878               for instance.  Only "m??"  patterns local to the current
1879               package are reset.
1880
1881                   while (<>) {
1882                       if (m?^$?) {
1883                                           # blank line between header and body
1884                       }
1885                   } continue {
1886                       reset if eof;       # clear m?? status for next file
1887                   }
1888
1889               Another example switched the first "latin1" encoding it finds
1890               to "utf8" in a pod file:
1891
1892                   s//utf8/ if m? ^ =encoding \h+ \K latin1 ?x;
1893
1894               The match-once behavior is controlled by the match delimiter
1895               being "?"; with any other delimiter this is the normal "m//"
1896               operator.
1897
1898               In the past, the leading "m" in "m?PATTERN?" was optional, but
1899               omitting it would produce a deprecation warning.  As of
1900               v5.22.0, omitting it produces a syntax error.  If you encounter
1901               this construct in older code, you can just add "m".
1902
1903       "s/PATTERN/REPLACEMENT/msixpodualngcer"
1904               Searches a string for a pattern, and if found, replaces that
1905               pattern with the replacement text and returns the number of
1906               substitutions made.  Otherwise it returns false (specifically,
1907               the empty string).
1908
1909               If the "/r" (non-destructive) option is used then it runs the
1910               substitution on a copy of the string and instead of returning
1911               the number of substitutions, it returns the copy whether or not
1912               a substitution occurred.  The original string is never changed
1913               when "/r" is used.  The copy will always be a plain string,
1914               even if the input is an object or a tied variable.
1915
1916               If no string is specified via the "=~" or "!~" operator, the $_
1917               variable is searched and modified.  Unless the "/r" option is
1918               used, the string specified must be a scalar variable, an array
1919               element, a hash element, or an assignment to one of those; that
1920               is, some sort of scalar lvalue.
1921
1922               If the delimiter chosen is a single quote, no variable
1923               interpolation is done on either the PATTERN or the REPLACEMENT.
1924               Otherwise, if the PATTERN contains a "$" that looks like a
1925               variable rather than an end-of-string test, the variable will
1926               be interpolated into the pattern at run-time.  If you want the
1927               pattern compiled only once the first time the variable is
1928               interpolated, use the "/o" option.  If the pattern evaluates to
1929               the empty string, the last successfully executed regular
1930               expression is used instead.  See perlre for further explanation
1931               on these.
1932
1933               Options are as with "m//" with the addition of the following
1934               replacement specific options:
1935
1936                   e   Evaluate the right side as an expression.
1937                   ee  Evaluate the right side as a string then eval the
1938                       result.
1939                   r   Return substitution and leave the original string
1940                       untouched.
1941
1942               Any non-whitespace delimiter may replace the slashes.  Add
1943               space after the "s" when using a character allowed in
1944               identifiers.  If single quotes are used, no interpretation is
1945               done on the replacement string (the "/e" modifier overrides
1946               this, however).  Note that Perl treats backticks as normal
1947               delimiters; the replacement text is not evaluated as a command.
1948               If the PATTERN is delimited by bracketing quotes, the
1949               REPLACEMENT has its own pair of quotes, which may or may not be
1950               bracketing quotes, for example, "s(foo)(bar)" or "s<foo>/bar/".
1951               A "/e" will cause the replacement portion to be treated as a
1952               full-fledged Perl expression and evaluated right then and
1953               there.  It is, however, syntax checked at compile-time.  A
1954               second "e" modifier will cause the replacement portion to be
1955               "eval"ed before being run as a Perl expression.
1956
1957               Examples:
1958
1959                   s/\bgreen\b/mauve/g;              # don't change wintergreen
1960
1961                   $path =~ s|/usr/bin|/usr/local/bin|;
1962
1963                   s/Login: $foo/Login: $bar/; # run-time pattern
1964
1965                   ($foo = $bar) =~ s/this/that/;      # copy first, then
1966                                                       # change
1967                   ($foo = "$bar") =~ s/this/that/;    # convert to string,
1968                                                       # copy, then change
1969                   $foo = $bar =~ s/this/that/r;       # Same as above using /r
1970                   $foo = $bar =~ s/this/that/r
1971                               =~ s/that/the other/r;  # Chained substitutes
1972                                                       # using /r
1973                   @foo = map { s/this/that/r } @bar   # /r is very useful in
1974                                                       # maps
1975
1976                   $count = ($paragraph =~ s/Mister\b/Mr./g);  # get change-cnt
1977
1978                   $_ = 'abc123xyz';
1979                   s/\d+/$&*2/e;               # yields 'abc246xyz'
1980                   s/\d+/sprintf("%5d",$&)/e;  # yields 'abc  246xyz'
1981                   s/\w/$& x 2/eg;             # yields 'aabbcc  224466xxyyzz'
1982
1983                   s/%(.)/$percent{$1}/g;      # change percent escapes; no /e
1984                   s/%(.)/$percent{$1} || $&/ge;       # expr now, so /e
1985                   s/^=(\w+)/pod($1)/ge;       # use function call
1986
1987                   $_ = 'abc123xyz';
1988                   $x = s/abc/def/r;           # $x is 'def123xyz' and
1989                                               # $_ remains 'abc123xyz'.
1990
1991                   # expand variables in $_, but dynamics only, using
1992                   # symbolic dereferencing
1993                   s/\$(\w+)/${$1}/g;
1994
1995                   # Add one to the value of any numbers in the string
1996                   s/(\d+)/1 + $1/eg;
1997
1998                   # Titlecase words in the last 30 characters only
1999                   substr($str, -30) =~ s/\b(\p{Alpha}+)\b/\u\L$1/g;
2000
2001                   # This will expand any embedded scalar variable
2002                   # (including lexicals) in $_ : First $1 is interpolated
2003                   # to the variable name, and then evaluated
2004                   s/(\$\w+)/$1/eeg;
2005
2006                   # Delete (most) C comments.
2007                   $program =~ s {
2008                       /\*     # Match the opening delimiter.
2009                       .*?     # Match a minimal number of characters.
2010                       \*/     # Match the closing delimiter.
2011                   } []gsx;
2012
2013                   s/^\s*(.*?)\s*$/$1/;        # trim whitespace in $_,
2014                                               # expensively
2015
2016                   for ($variable) {           # trim whitespace in $variable,
2017                                               # cheap
2018                       s/^\s+//;
2019                       s/\s+$//;
2020                   }
2021
2022                   s/([^ ]*) *([^ ]*)/$2 $1/;  # reverse 1st two fields
2023
2024               Note the use of "$" instead of "\" in the last example.  Unlike
2025               sed, we use the \<digit> form only in the left hand side.
2026               Anywhere else it's $<digit>.
2027
2028               Occasionally, you can't use just a "/g" to get all the changes
2029               to occur that you might want.  Here are two common cases:
2030
2031                   # put commas in the right places in an integer
2032                   1 while s/(\d)(\d\d\d)(?!\d)/$1,$2/g;
2033
2034                   # expand tabs to 8-column spacing
2035                   1 while s/\t+/' ' x (length($&)*8 - length($`)%8)/e;
2036
2037   Quote-Like Operators
2038       "q/STRING/"
2039       'STRING'
2040           A single-quoted, literal string.  A backslash represents a
2041           backslash unless followed by the delimiter or another backslash, in
2042           which case the delimiter or backslash is interpolated.
2043
2044               $foo = q!I said, "You said, 'She said it.'"!;
2045               $bar = q('This is it.');
2046               $baz = '\n';                # a two-character string
2047
2048       "qq/STRING/"
2049       "STRING"
2050           A double-quoted, interpolated string.
2051
2052               $_ .= qq
2053                (*** The previous line contains the naughty word "$1".\n)
2054                           if /\b(tcl|java|python)\b/i;      # :-)
2055               $baz = "\n";                # a one-character string
2056
2057       "qx/STRING/"
2058       "`STRING`"
2059           A string which is (possibly) interpolated and then executed as a
2060           system command with /bin/sh or its equivalent.  Shell wildcards,
2061           pipes, and redirections will be honored.  The collected standard
2062           output of the command is returned; standard error is unaffected.
2063           In scalar context, it comes back as a single (potentially multi-
2064           line) string, or "undef" if the command failed.  In list context,
2065           returns a list of lines (however you've defined lines with $/ or
2066           $INPUT_RECORD_SEPARATOR), or an empty list if the command failed.
2067
2068           Because backticks do not affect standard error, use shell file
2069           descriptor syntax (assuming the shell supports this) if you care to
2070           address this.  To capture a command's STDERR and STDOUT together:
2071
2072               $output = `cmd 2>&1`;
2073
2074           To capture a command's STDOUT but discard its STDERR:
2075
2076               $output = `cmd 2>/dev/null`;
2077
2078           To capture a command's STDERR but discard its STDOUT (ordering is
2079           important here):
2080
2081               $output = `cmd 2>&1 1>/dev/null`;
2082
2083           To exchange a command's STDOUT and STDERR in order to capture the
2084           STDERR but leave its STDOUT to come out the old STDERR:
2085
2086               $output = `cmd 3>&1 1>&2 2>&3 3>&-`;
2087
2088           To read both a command's STDOUT and its STDERR separately, it's
2089           easiest to redirect them separately to files, and then read from
2090           those files when the program is done:
2091
2092               system("program args 1>program.stdout 2>program.stderr");
2093
2094           The STDIN filehandle used by the command is inherited from Perl's
2095           STDIN.  For example:
2096
2097               open(SPLAT, "stuff")   || die "can't open stuff: $!";
2098               open(STDIN, "<&SPLAT") || die "can't dupe SPLAT: $!";
2099               print STDOUT `sort`;
2100
2101           will print the sorted contents of the file named "stuff".
2102
2103           Using single-quote as a delimiter protects the command from Perl's
2104           double-quote interpolation, passing it on to the shell instead:
2105
2106               $perl_info  = qx(ps $$);            # that's Perl's $$
2107               $shell_info = qx'ps $$';            # that's the new shell's $$
2108
2109           How that string gets evaluated is entirely subject to the command
2110           interpreter on your system.  On most platforms, you will have to
2111           protect shell metacharacters if you want them treated literally.
2112           This is in practice difficult to do, as it's unclear how to escape
2113           which characters.  See perlsec for a clean and safe example of a
2114           manual "fork()" and "exec()" to emulate backticks safely.
2115
2116           On some platforms (notably DOS-like ones), the shell may not be
2117           capable of dealing with multiline commands, so putting newlines in
2118           the string may not get you what you want.  You may be able to
2119           evaluate multiple commands in a single line by separating them with
2120           the command separator character, if your shell supports that (for
2121           example, ";" on many Unix shells and "&" on the Windows NT "cmd"
2122           shell).
2123
2124           Perl will attempt to flush all files opened for output before
2125           starting the child process, but this may not be supported on some
2126           platforms (see perlport).  To be safe, you may need to set $|
2127           ($AUTOFLUSH in "English") or call the "autoflush()" method of
2128           "IO::Handle" on any open handles.
2129
2130           Beware that some command shells may place restrictions on the
2131           length of the command line.  You must ensure your strings don't
2132           exceed this limit after any necessary interpolations.  See the
2133           platform-specific release notes for more details about your
2134           particular environment.
2135
2136           Using this operator can lead to programs that are difficult to
2137           port, because the shell commands called vary between systems, and
2138           may in fact not be present at all.  As one example, the "type"
2139           command under the POSIX shell is very different from the "type"
2140           command under DOS.  That doesn't mean you should go out of your way
2141           to avoid backticks when they're the right way to get something
2142           done.  Perl was made to be a glue language, and one of the things
2143           it glues together is commands.  Just understand what you're getting
2144           yourself into.
2145
2146           Like "system", backticks put the child process exit code in $?.  If
2147           you'd like to manually inspect failure, you can check all possible
2148           failure modes by inspecting $? like this:
2149
2150               if ($? == -1) {
2151                   print "failed to execute: $!\n";
2152               }
2153               elsif ($? & 127) {
2154                   printf "child died with signal %d, %s coredump\n",
2155                       ($? & 127),  ($? & 128) ? 'with' : 'without';
2156               }
2157               else {
2158                   printf "child exited with value %d\n", $? >> 8;
2159               }
2160
2161           Use the open pragma to control the I/O layers used when reading the
2162           output of the command, for example:
2163
2164             use open IN => ":encoding(UTF-8)";
2165             my $x = `cmd-producing-utf-8`;
2166
2167           See "I/O Operators" for more discussion.
2168
2169       "qw/STRING/"
2170           Evaluates to a list of the words extracted out of STRING, using
2171           embedded whitespace as the word delimiters.  It can be understood
2172           as being roughly equivalent to:
2173
2174               split(" ", q/STRING/);
2175
2176           the differences being that it generates a real list at compile
2177           time, and in scalar context it returns the last element in the
2178           list.  So this expression:
2179
2180               qw(foo bar baz)
2181
2182           is semantically equivalent to the list:
2183
2184               "foo", "bar", "baz"
2185
2186           Some frequently seen examples:
2187
2188               use POSIX qw( setlocale localeconv )
2189               @EXPORT = qw( foo bar baz );
2190
2191           A common mistake is to try to separate the words with commas or to
2192           put comments into a multi-line "qw"-string.  For this reason, the
2193           "use warnings" pragma and the -w switch (that is, the $^W variable)
2194           produces warnings if the STRING contains the "," or the "#"
2195           character.
2196
2197       "tr/SEARCHLIST/REPLACEMENTLIST/cdsr"
2198       "y/SEARCHLIST/REPLACEMENTLIST/cdsr"
2199           Transliterates all occurrences of the characters found in the
2200           search list with the corresponding character in the replacement
2201           list.  It returns the number of characters replaced or deleted.  If
2202           no string is specified via the "=~" or "!~" operator, the $_ string
2203           is transliterated.
2204
2205           If the "/r" (non-destructive) option is present, a new copy of the
2206           string is made and its characters transliterated, and this copy is
2207           returned no matter whether it was modified or not: the original
2208           string is always left unchanged.  The new copy is always a plain
2209           string, even if the input string is an object or a tied variable.
2210
2211           Unless the "/r" option is used, the string specified with "=~" must
2212           be a scalar variable, an array element, a hash element, or an
2213           assignment to one of those; in other words, an lvalue.
2214
2215           A character range may be specified with a hyphen, so "tr/A-J/0-9/"
2216           does the same replacement as "tr/ACEGIBDFHJ/0246813579/".  For sed
2217           devotees, "y" is provided as a synonym for "tr".  If the SEARCHLIST
2218           is delimited by bracketing quotes, the REPLACEMENTLIST must have
2219           its own pair of quotes, which may or may not be bracketing quotes;
2220           for example, "tr[aeiouy][yuoiea]" or "tr(+\-*/)/ABCD/".
2221
2222           Characters may be literals or any of the escape sequences accepted
2223           in double-quoted strings.  But there is no variable interpolation,
2224           so "$" and "@" are treated as literals.  A hyphen at the beginning
2225           or end, or preceded by a backslash is considered a literal.  Escape
2226           sequence details are in the table near the beginning of this
2227           section.
2228
2229           Note that "tr" does not do regular expression character classes
2230           such as "\d" or "\pL".  The "tr" operator is not equivalent to the
2231           tr(1) utility.  "tr[a-z][A-Z]" will uppercase the 26 letters "a"
2232           through "z", but for case changing not confined to ASCII, use "lc",
2233           "uc", "lcfirst", "ucfirst" (all documented in perlfunc), or the
2234           substitution operator "s/PATTERN/REPLACEMENT/" (with "\U", "\u",
2235           "\L", and "\l" string-interpolation escapes in the REPLACEMENT
2236           portion).
2237
2238           Most ranges are unportable between character sets, but certain ones
2239           signal Perl to do special handling to make them portable.  There
2240           are two classes of portable ranges.  The first are any subsets of
2241           the ranges "A-Z", "a-z", and "0-9", when expressed as literal
2242           characters.
2243
2244             tr/h-k/H-K/
2245
2246           capitalizes the letters "h", "i", "j", and "k" and nothing else, no
2247           matter what the platform's character set is.  In contrast, all of
2248
2249             tr/\x68-\x6B/\x48-\x4B/
2250             tr/h-\x6B/H-\x4B/
2251             tr/\x68-k/\x48-K/
2252
2253           do the same capitalizations as the previous example when run on
2254           ASCII platforms, but something completely different on EBCDIC ones.
2255
2256           The second class of portable ranges is invoked when one or both of
2257           the range's end points are expressed as "\N{...}"
2258
2259            $string =~ tr/\N{U+20}-\N{U+7E}//d;
2260
2261           removes from $string all the platform's characters which are
2262           equivalent to any of Unicode U+0020, U+0021, ... U+007D, U+007E.
2263           This is a portable range, and has the same effect on every platform
2264           it is run on.  It turns out that in this example, these are the
2265           ASCII printable characters.  So after this is run, $string has only
2266           controls and characters which have no ASCII equivalents.
2267
2268           But, even for portable ranges, it is not generally obvious what is
2269           included without having to look things up.  A sound principle is to
2270           use only ranges that begin from and end at either ASCII alphabetics
2271           of equal case ("b-e", "B-E"), or digits ("1-4").  Anything else is
2272           unclear (and unportable unless "\N{...}" is used).  If in doubt,
2273           spell out the character sets in full.
2274
2275           Options:
2276
2277               c   Complement the SEARCHLIST.
2278               d   Delete found but unreplaced characters.
2279               s   Squash duplicate replaced characters.
2280               r   Return the modified string and leave the original string
2281                   untouched.
2282
2283           If the "/c" modifier is specified, the SEARCHLIST character set is
2284           complemented.  If the "/d" modifier is specified, any characters
2285           specified by SEARCHLIST not found in REPLACEMENTLIST are deleted.
2286           (Note that this is slightly more flexible than the behavior of some
2287           tr programs, which delete anything they find in the SEARCHLIST,
2288           period.)  If the "/s" modifier is specified, sequences of
2289           characters that were transliterated to the same character are
2290           squashed down to a single instance of the character.
2291
2292           If the "/d" modifier is used, the REPLACEMENTLIST is always
2293           interpreted exactly as specified.  Otherwise, if the
2294           REPLACEMENTLIST is shorter than the SEARCHLIST, the final character
2295           is replicated till it is long enough.  If the REPLACEMENTLIST is
2296           empty, the SEARCHLIST is replicated.  This latter is useful for
2297           counting characters in a class or for squashing character sequences
2298           in a class.
2299
2300           Examples:
2301
2302               $ARGV[1] =~ tr/A-Z/a-z/;    # canonicalize to lower case ASCII
2303
2304               $cnt = tr/*/*/;             # count the stars in $_
2305
2306               $cnt = $sky =~ tr/*/*/;     # count the stars in $sky
2307
2308               $cnt = tr/0-9//;            # count the digits in $_
2309
2310               tr/a-zA-Z//s;               # bookkeeper -> bokeper
2311
2312               ($HOST = $host) =~ tr/a-z/A-Z/;
2313                $HOST = $host  =~ tr/a-z/A-Z/r;   # same thing
2314
2315               $HOST = $host =~ tr/a-z/A-Z/r    # chained with s///r
2316                             =~ s/:/ -p/r;
2317
2318               tr/a-zA-Z/ /cs;             # change non-alphas to single space
2319
2320               @stripped = map tr/a-zA-Z/ /csr, @original;
2321                                           # /r with map
2322
2323               tr [\200-\377]
2324                  [\000-\177];             # wickedly delete 8th bit
2325
2326           If multiple transliterations are given for a character, only the
2327           first one is used:
2328
2329               tr/AAA/XYZ/
2330
2331           will transliterate any A to X.
2332
2333           Because the transliteration table is built at compile time, neither
2334           the SEARCHLIST nor the REPLACEMENTLIST are subjected to double
2335           quote interpolation.  That means that if you want to use variables,
2336           you must use an "eval()":
2337
2338               eval "tr/$oldlist/$newlist/";
2339               die $@ if $@;
2340
2341               eval "tr/$oldlist/$newlist/, 1" or die $@;
2342
2343       "<<EOF"
2344           A line-oriented form of quoting is based on the shell "here-
2345           document" syntax.  Following a "<<" you specify a string to
2346           terminate the quoted material, and all lines following the current
2347           line down to the terminating string are the value of the item.
2348
2349           Prefixing the terminating string with a "~" specifies that you want
2350           to use "Indented Here-docs" (see below).
2351
2352           The terminating string may be either an identifier (a word), or
2353           some quoted text.  An unquoted identifier works like double quotes.
2354           There may not be a space between the "<<" and the identifier,
2355           unless the identifier is explicitly quoted.  (If you put a space it
2356           will be treated as a null identifier, which is valid, and matches
2357           the first empty line.)  The terminating string must appear by
2358           itself (unquoted and with no surrounding whitespace) on the
2359           terminating line.
2360
2361           If the terminating string is quoted, the type of quotes used
2362           determine the treatment of the text.
2363
2364           Double Quotes
2365               Double quotes indicate that the text will be interpolated using
2366               exactly the same rules as normal double quoted strings.
2367
2368                      print <<EOF;
2369                   The price is $Price.
2370                   EOF
2371
2372                      print << "EOF"; # same as above
2373                   The price is $Price.
2374                   EOF
2375
2376           Single Quotes
2377               Single quotes indicate the text is to be treated literally with
2378               no interpolation of its content.  This is similar to single
2379               quoted strings except that backslashes have no special meaning,
2380               with "\\" being treated as two backslashes and not one as they
2381               would in every other quoting construct.
2382
2383               Just as in the shell, a backslashed bareword following the "<<"
2384               means the same thing as a single-quoted string does:
2385
2386                       $cost = <<'VISTA';  # hasta la ...
2387                   That'll be $10 please, ma'am.
2388                   VISTA
2389
2390                       $cost = <<\VISTA;   # Same thing!
2391                   That'll be $10 please, ma'am.
2392                   VISTA
2393
2394               This is the only form of quoting in perl where there is no need
2395               to worry about escaping content, something that code generators
2396               can and do make good use of.
2397
2398           Backticks
2399               The content of the here doc is treated just as it would be if
2400               the string were embedded in backticks.  Thus the content is
2401               interpolated as though it were double quoted and then executed
2402               via the shell, with the results of the execution returned.
2403
2404                      print << `EOC`; # execute command and get results
2405                   echo hi there
2406                   EOC
2407
2408           Indented Here-docs
2409               The here-doc modifier "~" allows you to indent your here-docs
2410               to make the code more readable:
2411
2412                   if ($some_var) {
2413                     print <<~EOF;
2414                       This is a here-doc
2415                       EOF
2416                   }
2417
2418               This will print...
2419
2420                   This is a here-doc
2421
2422               ...with no leading whitespace.
2423
2424               The delimiter is used to determine the exact whitespace to
2425               remove from the beginning of each line.  All lines must have at
2426               least the same starting whitespace (except lines only
2427               containing a newline) or perl will croak.  Tabs and spaces can
2428               be mixed, but are matched exactly.  One tab will not be equal
2429               to 8 spaces!
2430
2431               Additional beginning whitespace (beyond what preceded the
2432               delimiter) will be preserved:
2433
2434                   print <<~EOF;
2435                     This text is not indented
2436                       This text is indented with two spaces
2437                               This text is indented with two tabs
2438                     EOF
2439
2440               Finally, the modifier may be used with all of the forms
2441               mentioned above:
2442
2443                   <<~\EOF;
2444                   <<~'EOF'
2445                   <<~"EOF"
2446                   <<~`EOF`
2447
2448               And whitespace may be used between the "~" and quoted
2449               delimiters:
2450
2451                   <<~ 'EOF'; # ... "EOF", `EOF`
2452
2453           It is possible to stack multiple here-docs in a row:
2454
2455                  print <<"foo", <<"bar"; # you can stack them
2456               I said foo.
2457               foo
2458               I said bar.
2459               bar
2460
2461                  myfunc(<< "THIS", 23, <<'THAT');
2462               Here's a line
2463               or two.
2464               THIS
2465               and here's another.
2466               THAT
2467
2468           Just don't forget that you have to put a semicolon on the end to
2469           finish the statement, as Perl doesn't know you're not going to try
2470           to do this:
2471
2472                  print <<ABC
2473               179231
2474               ABC
2475                  + 20;
2476
2477           If you want to remove the line terminator from your here-docs, use
2478           "chomp()".
2479
2480               chomp($string = <<'END');
2481               This is a string.
2482               END
2483
2484           If you want your here-docs to be indented with the rest of the
2485           code, you'll need to remove leading whitespace from each line
2486           manually:
2487
2488               ($quote = <<'FINIS') =~ s/^\s+//gm;
2489                  The Road goes ever on and on,
2490                  down from the door where it began.
2491               FINIS
2492
2493           If you use a here-doc within a delimited construct, such as in
2494           "s///eg", the quoted material must still come on the line following
2495           the "<<FOO" marker, which means it may be inside the delimited
2496           construct:
2497
2498               s/this/<<E . 'that'
2499               the other
2500               E
2501                . 'more '/eg;
2502
2503           It works this way as of Perl 5.18.  Historically, it was
2504           inconsistent, and you would have to write
2505
2506               s/this/<<E . 'that'
2507                . 'more '/eg;
2508               the other
2509               E
2510
2511           outside of string evals.
2512
2513           Additionally, quoting rules for the end-of-string identifier are
2514           unrelated to Perl's quoting rules.  "q()", "qq()", and the like are
2515           not supported in place of '' and "", and the only interpolation is
2516           for backslashing the quoting character:
2517
2518               print << "abc\"def";
2519               testing...
2520               abc"def
2521
2522           Finally, quoted strings cannot span multiple lines.  The general
2523           rule is that the identifier must be a string literal.  Stick with
2524           that, and you should be safe.
2525
2526   Gory details of parsing quoted constructs
2527       When presented with something that might have several different
2528       interpretations, Perl uses the DWIM (that's "Do What I Mean") principle
2529       to pick the most probable interpretation.  This strategy is so
2530       successful that Perl programmers often do not suspect the ambivalence
2531       of what they write.  But from time to time, Perl's notions differ
2532       substantially from what the author honestly meant.
2533
2534       This section hopes to clarify how Perl handles quoted constructs.
2535       Although the most common reason to learn this is to unravel
2536       labyrinthine regular expressions, because the initial steps of parsing
2537       are the same for all quoting operators, they are all discussed
2538       together.
2539
2540       The most important Perl parsing rule is the first one discussed below:
2541       when processing a quoted construct, Perl first finds the end of that
2542       construct, then interprets its contents.  If you understand this rule,
2543       you may skip the rest of this section on the first reading.  The other
2544       rules are likely to contradict the user's expectations much less
2545       frequently than this first one.
2546
2547       Some passes discussed below are performed concurrently, but because
2548       their results are the same, we consider them individually.  For
2549       different quoting constructs, Perl performs different numbers of
2550       passes, from one to four, but these passes are always performed in the
2551       same order.
2552
2553       Finding the end
2554           The first pass is finding the end of the quoted construct.  This
2555           results in saving to a safe location a copy of the text (between
2556           the starting and ending delimiters), normalized as necessary to
2557           avoid needing to know what the original delimiters were.
2558
2559           If the construct is a here-doc, the ending delimiter is a line that
2560           has a terminating string as the content.  Therefore "<<EOF" is
2561           terminated by "EOF" immediately followed by "\n" and starting from
2562           the first column of the terminating line.  When searching for the
2563           terminating line of a here-doc, nothing is skipped.  In other
2564           words, lines after the here-doc syntax are compared with the
2565           terminating string line by line.
2566
2567           For the constructs except here-docs, single characters are used as
2568           starting and ending delimiters.  If the starting delimiter is an
2569           opening punctuation (that is "(", "[", "{", or "<"), the ending
2570           delimiter is the corresponding closing punctuation (that is ")",
2571           "]", "}", or ">").  If the starting delimiter is an unpaired
2572           character like "/" or a closing punctuation, the ending delimiter
2573           is the same as the starting delimiter.  Therefore a "/" terminates
2574           a "qq//" construct, while a "]" terminates both "qq[]" and "qq]]"
2575           constructs.
2576
2577           When searching for single-character delimiters, escaped delimiters
2578           and "\\" are skipped.  For example, while searching for terminating
2579           "/", combinations of "\\" and "\/" are skipped.  If the delimiters
2580           are bracketing, nested pairs are also skipped.  For example, while
2581           searching for a closing "]" paired with the opening "[",
2582           combinations of "\\", "\]", and "\[" are all skipped, and nested
2583           "[" and "]" are skipped as well.  However, when backslashes are
2584           used as the delimiters (like "qq\\" and "tr\\\"), nothing is
2585           skipped.  During the search for the end, backslashes that escape
2586           delimiters or other backslashes are removed (exactly speaking, they
2587           are not copied to the safe location).
2588
2589           For constructs with three-part delimiters ("s///", "y///", and
2590           "tr///"), the search is repeated once more.  If the first delimiter
2591           is not an opening punctuation, the three delimiters must be the
2592           same, such as "s!!!" and "tr)))", in which case the second
2593           delimiter terminates the left part and starts the right part at
2594           once.  If the left part is delimited by bracketing punctuation
2595           (that is "()", "[]", "{}", or "<>"), the right part needs another
2596           pair of delimiters such as "s(){}" and "tr[]//".  In these cases,
2597           whitespace and comments are allowed between the two parts, although
2598           the comment must follow at least one whitespace character;
2599           otherwise a character expected as the start of the comment may be
2600           regarded as the starting delimiter of the right part.
2601
2602           During this search no attention is paid to the semantics of the
2603           construct.  Thus:
2604
2605               "$hash{"$foo/$bar"}"
2606
2607           or:
2608
2609               m/
2610                 bar       # NOT a comment, this slash / terminated m//!
2611                /x
2612
2613           do not form legal quoted expressions.   The quoted part ends on the
2614           first """ and "/", and the rest happens to be a syntax error.
2615           Because the slash that terminated "m//" was followed by a "SPACE",
2616           the example above is not "m//x", but rather "m//" with no "/x"
2617           modifier.  So the embedded "#" is interpreted as a literal "#".
2618
2619           Also no attention is paid to "\c\" (multichar control char syntax)
2620           during this search.  Thus the second "\" in "qq/\c\/" is
2621           interpreted as a part of "\/", and the following "/" is not
2622           recognized as a delimiter.  Instead, use "\034" or "\x1c" at the
2623           end of quoted constructs.
2624
2625       Interpolation
2626           The next step is interpolation in the text obtained, which is now
2627           delimiter-independent.  There are multiple cases.
2628
2629           "<<'EOF'"
2630               No interpolation is performed.  Note that the combination "\\"
2631               is left intact, since escaped delimiters are not available for
2632               here-docs.
2633
2634           "m''", the pattern of "s'''"
2635               No interpolation is performed at this stage.  Any backslashed
2636               sequences including "\\" are treated at the stage to "parsing
2637               regular expressions".
2638
2639           '', "q//", "tr'''", "y'''", the replacement of "s'''"
2640               The only interpolation is removal of "\" from pairs of "\\".
2641               Therefore "-" in "tr'''" and "y'''" is treated literally as a
2642               hyphen and no character range is available.  "\1" in the
2643               replacement of "s'''" does not work as $1.
2644
2645           "tr///", "y///"
2646               No variable interpolation occurs.  String modifying
2647               combinations for case and quoting such as "\Q", "\U", and "\E"
2648               are not recognized.  The other escape sequences such as "\200"
2649               and "\t" and backslashed characters such as "\\" and "\-" are
2650               converted to appropriate literals.  The character "-" is
2651               treated specially and therefore "\-" is treated as a literal
2652               "-".
2653
2654           "", "``", "qq//", "qx//", "<file*glob>", "<<"EOF""
2655               "\Q", "\U", "\u", "\L", "\l", "\F" (possibly paired with "\E")
2656               are converted to corresponding Perl constructs.  Thus,
2657               "$foo\Qbaz$bar" is converted to
2658               "$foo . (quotemeta("baz" . $bar))" internally.  The other
2659               escape sequences such as "\200" and "\t" and backslashed
2660               characters such as "\\" and "\-" are replaced with appropriate
2661               expansions.
2662
2663               Let it be stressed that whatever falls between "\Q" and "\E" is
2664               interpolated in the usual way.  Something like "\Q\\E" has no
2665               "\E" inside.  Instead, it has "\Q", "\\", and "E", so the
2666               result is the same as for "\\\\E".  As a general rule,
2667               backslashes between "\Q" and "\E" may lead to counterintuitive
2668               results.  So, "\Q\t\E" is converted to "quotemeta("\t")", which
2669               is the same as "\\\t" (since TAB is not alphanumeric).  Note
2670               also that:
2671
2672                 $str = '\t';
2673                 return "\Q$str";
2674
2675               may be closer to the conjectural intention of the writer of
2676               "\Q\t\E".
2677
2678               Interpolated scalars and arrays are converted internally to the
2679               "join" and "." catenation operations.  Thus, "$foo XXX '@arr'"
2680               becomes:
2681
2682                 $foo . " XXX '" . (join $", @arr) . "'";
2683
2684               All operations above are performed simultaneously, left to
2685               right.
2686
2687               Because the result of "\Q STRING \E" has all metacharacters
2688               quoted, there is no way to insert a literal "$" or "@" inside a
2689               "\Q\E" pair.  If protected by "\", "$" will be quoted to become
2690               "\\\$"; if not, it is interpreted as the start of an
2691               interpolated scalar.
2692
2693               Note also that the interpolation code needs to make a decision
2694               on where the interpolated scalar ends.  For instance, whether
2695               "a $x -> {c}" really means:
2696
2697                 "a " . $x . " -> {c}";
2698
2699               or:
2700
2701                 "a " . $x -> {c};
2702
2703               Most of the time, the longest possible text that does not
2704               include spaces between components and which contains matching
2705               braces or brackets.  because the outcome may be determined by
2706               voting based on heuristic estimators, the result is not
2707               strictly predictable.  Fortunately, it's usually correct for
2708               ambiguous cases.
2709
2710           the replacement of "s///"
2711               Processing of "\Q", "\U", "\u", "\L", "\l", "\F" and
2712               interpolation happens as with "qq//" constructs.
2713
2714               It is at this step that "\1" is begrudgingly converted to $1 in
2715               the replacement text of "s///", in order to correct the
2716               incorrigible sed hackers who haven't picked up the saner idiom
2717               yet.  A warning is emitted if the "use warnings" pragma or the
2718               -w command-line flag (that is, the $^W variable) was set.
2719
2720           "RE" in "m?RE?", "/RE/", "m/RE/", "s/RE/foo/",
2721               Processing of "\Q", "\U", "\u", "\L", "\l", "\F", "\E", and
2722               interpolation happens (almost) as with "qq//" constructs.
2723
2724               Processing of "\N{...}" is also done here, and compiled into an
2725               intermediate form for the regex compiler.  (This is because, as
2726               mentioned below, the regex compilation may be done at execution
2727               time, and "\N{...}" is a compile-time construct.)
2728
2729               However any other combinations of "\" followed by a character
2730               are not substituted but only skipped, in order to parse them as
2731               regular expressions at the following step.  As "\c" is skipped
2732               at this step, "@" of "\c@" in RE is possibly treated as an
2733               array symbol (for example @foo), even though the same text in
2734               "qq//" gives interpolation of "\c@".
2735
2736               Code blocks such as "(?{BLOCK})" are handled by temporarily
2737               passing control back to the perl parser, in a similar way that
2738               an interpolated array subscript expression such as
2739               "foo$array[1+f("[xyz")]bar" would be.
2740
2741               Moreover, inside "(?{BLOCK})", "(?# comment )", and a
2742               "#"-comment in a "/x"-regular expression, no processing is
2743               performed whatsoever.  This is the first step at which the
2744               presence of the "/x" modifier is relevant.
2745
2746               Interpolation in patterns has several quirks: $|, $(, $), "@+"
2747               and "@-" are not interpolated, and constructs $var[SOMETHING]
2748               are voted (by several different estimators) to be either an
2749               array element or $var followed by an RE alternative.  This is
2750               where the notation "${arr[$bar]}" comes handy: "/${arr[0-9]}/"
2751               is interpreted as array element "-9", not as a regular
2752               expression from the variable $arr followed by a digit, which
2753               would be the interpretation of "/$arr[0-9]/".  Since voting
2754               among different estimators may occur, the result is not
2755               predictable.
2756
2757               The lack of processing of "\\" creates specific restrictions on
2758               the post-processed text.  If the delimiter is "/", one cannot
2759               get the combination "\/" into the result of this step.  "/"
2760               will finish the regular expression, "\/" will be stripped to
2761               "/" on the previous step, and "\\/" will be left as is.
2762               Because "/" is equivalent to "\/" inside a regular expression,
2763               this does not matter unless the delimiter happens to be
2764               character special to the RE engine, such as in "s*foo*bar*",
2765               "m[foo]", or "m?foo?"; or an alphanumeric char, as in:
2766
2767                 m m ^ a \s* b mmx;
2768
2769               In the RE above, which is intentionally obfuscated for
2770               illustration, the delimiter is "m", the modifier is "mx", and
2771               after delimiter-removal the RE is the same as for
2772               "m/ ^ a \s* b /mx".  There's more than one reason you're
2773               encouraged to restrict your delimiters to non-alphanumeric,
2774               non-whitespace choices.
2775
2776           This step is the last one for all constructs except regular
2777           expressions, which are processed further.
2778
2779       parsing regular expressions
2780           Previous steps were performed during the compilation of Perl code,
2781           but this one happens at run time, although it may be optimized to
2782           be calculated at compile time if appropriate.  After preprocessing
2783           described above, and possibly after evaluation if concatenation,
2784           joining, casing translation, or metaquoting are involved, the
2785           resulting string is passed to the RE engine for compilation.
2786
2787           Whatever happens in the RE engine might be better discussed in
2788           perlre, but for the sake of continuity, we shall do so here.
2789
2790           This is another step where the presence of the "/x" modifier is
2791           relevant.  The RE engine scans the string from left to right and
2792           converts it into a finite automaton.
2793
2794           Backslashed characters are either replaced with corresponding
2795           literal strings (as with "\{"), or else they generate special nodes
2796           in the finite automaton (as with "\b").  Characters special to the
2797           RE engine (such as "|") generate corresponding nodes or groups of
2798           nodes.  "(?#...)" comments are ignored.  All the rest is either
2799           converted to literal strings to match, or else is ignored (as is
2800           whitespace and "#"-style comments if "/x" is present).
2801
2802           Parsing of the bracketed character class construct, "[...]", is
2803           rather different than the rule used for the rest of the pattern.
2804           The terminator of this construct is found using the same rules as
2805           for finding the terminator of a "{}"-delimited construct, the only
2806           exception being that "]" immediately following "[" is treated as
2807           though preceded by a backslash.
2808
2809           The terminator of runtime "(?{...})" is found by temporarily
2810           switching control to the perl parser, which should stop at the
2811           point where the logically balancing terminating "}" is found.
2812
2813           It is possible to inspect both the string given to RE engine and
2814           the resulting finite automaton.  See the arguments
2815           "debug"/"debugcolor" in the "use re" pragma, as well as Perl's -Dr
2816           command-line switch documented in "Command Switches" in perlrun.
2817
2818       Optimization of regular expressions
2819           This step is listed for completeness only.  Since it does not
2820           change semantics, details of this step are not documented and are
2821           subject to change without notice.  This step is performed over the
2822           finite automaton that was generated during the previous pass.
2823
2824           It is at this stage that "split()" silently optimizes "/^/" to mean
2825           "/^/m".
2826
2827   I/O Operators
2828       There are several I/O operators you should know about.
2829
2830       A string enclosed by backticks (grave accents) first undergoes double-
2831       quote interpolation.  It is then interpreted as an external command,
2832       and the output of that command is the value of the backtick string,
2833       like in a shell.  In scalar context, a single string consisting of all
2834       output is returned.  In list context, a list of values is returned, one
2835       per line of output.  (You can set $/ to use a different line
2836       terminator.)  The command is executed each time the pseudo-literal is
2837       evaluated.  The status value of the command is returned in $? (see
2838       perlvar for the interpretation of $?).  Unlike in csh, no translation
2839       is done on the return data--newlines remain newlines.  Unlike in any of
2840       the shells, single quotes do not hide variable names in the command
2841       from interpretation.  To pass a literal dollar-sign through to the
2842       shell you need to hide it with a backslash.  The generalized form of
2843       backticks is "qx//".  (Because backticks always undergo shell expansion
2844       as well, see perlsec for security concerns.)
2845
2846       In scalar context, evaluating a filehandle in angle brackets yields the
2847       next line from that file (the newline, if any, included), or "undef" at
2848       end-of-file or on error.  When $/ is set to "undef" (sometimes known as
2849       file-slurp mode) and the file is empty, it returns '' the first time,
2850       followed by "undef" subsequently.
2851
2852       Ordinarily you must assign the returned value to a variable, but there
2853       is one situation where an automatic assignment happens.  If and only if
2854       the input symbol is the only thing inside the conditional of a "while"
2855       statement (even if disguised as a "for(;;)" loop), the value is
2856       automatically assigned to the global variable $_, destroying whatever
2857       was there previously.  (This may seem like an odd thing to you, but
2858       you'll use the construct in almost every Perl script you write.)  The
2859       $_ variable is not implicitly localized.  You'll have to put a
2860       "local $_;" before the loop if you want that to happen.
2861
2862       The following lines are equivalent:
2863
2864           while (defined($_ = <STDIN>)) { print; }
2865           while ($_ = <STDIN>) { print; }
2866           while (<STDIN>) { print; }
2867           for (;<STDIN>;) { print; }
2868           print while defined($_ = <STDIN>);
2869           print while ($_ = <STDIN>);
2870           print while <STDIN>;
2871
2872       This also behaves similarly, but assigns to a lexical variable instead
2873       of to $_:
2874
2875           while (my $line = <STDIN>) { print $line }
2876
2877       In these loop constructs, the assigned value (whether assignment is
2878       automatic or explicit) is then tested to see whether it is defined.
2879       The defined test avoids problems where the line has a string value that
2880       would be treated as false by Perl; for example a "" or a "0" with no
2881       trailing newline.  If you really mean for such values to terminate the
2882       loop, they should be tested for explicitly:
2883
2884           while (($_ = <STDIN>) ne '0') { ... }
2885           while (<STDIN>) { last unless $_; ... }
2886
2887       In other boolean contexts, "<FILEHANDLE>" without an explicit "defined"
2888       test or comparison elicits a warning if the "use warnings" pragma or
2889       the -w command-line switch (the $^W variable) is in effect.
2890
2891       The filehandles STDIN, STDOUT, and STDERR are predefined.  (The
2892       filehandles "stdin", "stdout", and "stderr" will also work except in
2893       packages, where they would be interpreted as local identifiers rather
2894       than global.)  Additional filehandles may be created with the "open()"
2895       function, amongst others.  See perlopentut and "open" in perlfunc for
2896       details on this.
2897
2898       If a "<FILEHANDLE>" is used in a context that is looking for a list, a
2899       list comprising all input lines is returned, one line per list element.
2900       It's easy to grow to a rather large data space this way, so use with
2901       care.
2902
2903       "<FILEHANDLE>"  may also be spelled "readline(*FILEHANDLE)".  See
2904       "readline" in perlfunc.
2905
2906       The null filehandle "<>" is special: it can be used to emulate the
2907       behavior of sed and awk, and any other Unix filter program that takes a
2908       list of filenames, doing the same to each line of input from all of
2909       them.  Input from "<>" comes either from standard input, or from each
2910       file listed on the command line.  Here's how it works: the first time
2911       "<>" is evaluated, the @ARGV array is checked, and if it is empty,
2912       $ARGV[0] is set to "-", which when opened gives you standard input.
2913       The @ARGV array is then processed as a list of filenames.  The loop
2914
2915           while (<>) {
2916               ...                     # code for each line
2917           }
2918
2919       is equivalent to the following Perl-like pseudo code:
2920
2921           unshift(@ARGV, '-') unless @ARGV;
2922           while ($ARGV = shift) {
2923               open(ARGV, $ARGV);
2924               while (<ARGV>) {
2925                   ...         # code for each line
2926               }
2927           }
2928
2929       except that it isn't so cumbersome to say, and will actually work.  It
2930       really does shift the @ARGV array and put the current filename into the
2931       $ARGV variable.  It also uses filehandle ARGV internally.  "<>" is just
2932       a synonym for "<ARGV>", which is magical.  (The pseudo code above
2933       doesn't work because it treats "<ARGV>" as non-magical.)
2934
2935       Since the null filehandle uses the two argument form of "open" in
2936       perlfunc it interprets special characters, so if you have a script like
2937       this:
2938
2939           while (<>) {
2940               print;
2941           }
2942
2943       and call it with "perl dangerous.pl 'rm -rfv *|'", it actually opens a
2944       pipe, executes the "rm" command and reads "rm"'s output from that pipe.
2945       If you want all items in @ARGV to be interpreted as file names, you can
2946       use the module "ARGV::readonly" from CPAN, or use the double bracket:
2947
2948           while (<<>>) {
2949               print;
2950           }
2951
2952       Using double angle brackets inside of a while causes the open to use
2953       the three argument form (with the second argument being "<"), so all
2954       arguments in "ARGV" are treated as literal filenames (including "-").
2955       (Note that for convenience, if you use "<<>>" and if @ARGV is empty, it
2956       will still read from the standard input.)
2957
2958       You can modify @ARGV before the first "<>" as long as the array ends up
2959       containing the list of filenames you really want.  Line numbers ($.)
2960       continue as though the input were one big happy file.  See the example
2961       in "eof" in perlfunc for how to reset line numbers on each file.
2962
2963       If you want to set @ARGV to your own list of files, go right ahead.
2964       This sets @ARGV to all plain text files if no @ARGV was given:
2965
2966           @ARGV = grep { -f && -T } glob('*') unless @ARGV;
2967
2968       You can even set them to pipe commands.  For example, this
2969       automatically filters compressed arguments through gzip:
2970
2971           @ARGV = map { /\.(gz|Z)$/ ? "gzip -dc < $_ |" : $_ } @ARGV;
2972
2973       If you want to pass switches into your script, you can use one of the
2974       "Getopts" modules or put a loop on the front like this:
2975
2976           while ($_ = $ARGV[0], /^-/) {
2977               shift;
2978               last if /^--$/;
2979               if (/^-D(.*)/) { $debug = $1 }
2980               if (/^-v/)     { $verbose++  }
2981               # ...           # other switches
2982           }
2983
2984           while (<>) {
2985               # ...           # code for each line
2986           }
2987
2988       The "<>" symbol will return "undef" for end-of-file only once.  If you
2989       call it again after this, it will assume you are processing another
2990       @ARGV list, and if you haven't set @ARGV, will read input from STDIN.
2991
2992       If what the angle brackets contain is a simple scalar variable (for
2993       example, $foo), then that variable contains the name of the filehandle
2994       to input from, or its typeglob, or a reference to the same.  For
2995       example:
2996
2997           $fh = \*STDIN;
2998           $line = <$fh>;
2999
3000       If what's within the angle brackets is neither a filehandle nor a
3001       simple scalar variable containing a filehandle name, typeglob, or
3002       typeglob reference, it is interpreted as a filename pattern to be
3003       globbed, and either a list of filenames or the next filename in the
3004       list is returned, depending on context.  This distinction is determined
3005       on syntactic grounds alone.  That means "<$x>" is always a "readline()"
3006       from an indirect handle, but "<$hash{key}>" is always a "glob()".
3007       That's because $x is a simple scalar variable, but $hash{key} is
3008       not--it's a hash element.  Even "<$x >" (note the extra space) is
3009       treated as "glob("$x ")", not "readline($x)".
3010
3011       One level of double-quote interpretation is done first, but you can't
3012       say "<$foo>" because that's an indirect filehandle as explained in the
3013       previous paragraph.  (In older versions of Perl, programmers would
3014       insert curly brackets to force interpretation as a filename glob:
3015       "<${foo}>".  These days, it's considered cleaner to call the internal
3016       function directly as "glob($foo)", which is probably the right way to
3017       have done it in the first place.)  For example:
3018
3019           while (<*.c>) {
3020               chmod 0644, $_;
3021           }
3022
3023       is roughly equivalent to:
3024
3025           open(FOO, "echo *.c | tr -s ' \t\r\f' '\\012\\012\\012\\012'|");
3026           while (<FOO>) {
3027               chomp;
3028               chmod 0644, $_;
3029           }
3030
3031       except that the globbing is actually done internally using the standard
3032       "File::Glob" extension.  Of course, the shortest way to do the above
3033       is:
3034
3035           chmod 0644, <*.c>;
3036
3037       A (file)glob evaluates its (embedded) argument only when it is starting
3038       a new list.  All values must be read before it will start over.  In
3039       list context, this isn't important because you automatically get them
3040       all anyway.  However, in scalar context the operator returns the next
3041       value each time it's called, or "undef" when the list has run out.  As
3042       with filehandle reads, an automatic "defined" is generated when the
3043       glob occurs in the test part of a "while", because legal glob returns
3044       (for example, a file called 0) would otherwise terminate the loop.
3045       Again, "undef" is returned only once.  So if you're expecting a single
3046       value from a glob, it is much better to say
3047
3048           ($file) = <blurch*>;
3049
3050       than
3051
3052           $file = <blurch*>;
3053
3054       because the latter will alternate between returning a filename and
3055       returning false.
3056
3057       If you're trying to do variable interpolation, it's definitely better
3058       to use the "glob()" function, because the older notation can cause
3059       people to become confused with the indirect filehandle notation.
3060
3061           @files = glob("$dir/*.[ch]");
3062           @files = glob($files[$i]);
3063
3064   Constant Folding
3065       Like C, Perl does a certain amount of expression evaluation at compile
3066       time whenever it determines that all arguments to an operator are
3067       static and have no side effects.  In particular, string concatenation
3068       happens at compile time between literals that don't do variable
3069       substitution.  Backslash interpolation also happens at compile time.
3070       You can say
3071
3072             'Now is the time for all'
3073           . "\n"
3074           .  'good men to come to.'
3075
3076       and this all reduces to one string internally.  Likewise, if you say
3077
3078           foreach $file (@filenames) {
3079               if (-s $file > 5 + 100 * 2**16) {  }
3080           }
3081
3082       the compiler precomputes the number which that expression represents so
3083       that the interpreter won't have to.
3084
3085   No-ops
3086       Perl doesn't officially have a no-op operator, but the bare constants 0
3087       and 1 are special-cased not to produce a warning in void context, so
3088       you can for example safely do
3089
3090           1 while foo();
3091
3092   Bitwise String Operators
3093       Bitstrings of any size may be manipulated by the bitwise operators ("~
3094       | & ^").
3095
3096       If the operands to a binary bitwise op are strings of different sizes,
3097       | and ^ ops act as though the shorter operand had additional zero bits
3098       on the right, while the & op acts as though the longer operand were
3099       truncated to the length of the shorter.  The granularity for such
3100       extension or truncation is one or more bytes.
3101
3102           # ASCII-based examples
3103           print "j p \n" ^ " a h";            # prints "JAPH\n"
3104           print "JA" | "  ph\n";              # prints "japh\n"
3105           print "japh\nJunk" & '_____';       # prints "JAPH\n";
3106           print 'p N$' ^ " E<H\n";            # prints "Perl\n";
3107
3108       If you are intending to manipulate bitstrings, be certain that you're
3109       supplying bitstrings: If an operand is a number, that will imply a
3110       numeric bitwise operation.  You may explicitly show which type of
3111       operation you intend by using "" or "0+", as in the examples below.
3112
3113           $foo =  150  |  105;        # yields 255  (0x96 | 0x69 is 0xFF)
3114           $foo = '150' |  105;        # yields 255
3115           $foo =  150  | '105';       # yields 255
3116           $foo = '150' | '105';       # yields string '155' (under ASCII)
3117
3118           $baz = 0+$foo & 0+$bar;     # both ops explicitly numeric
3119           $biz = "$foo" ^ "$bar";     # both ops explicitly stringy
3120
3121       This somewhat unpredictable behavior can be avoided with the
3122       experimental "bitwise" feature, new in Perl 5.22.  You can enable it
3123       via "use feature 'bitwise'".  By default, it will warn unless the
3124       "experimental::bitwise" warnings category has been disabled.
3125       ("use experimental 'bitwise'" will enable the feature and disable the
3126       warning.)  Under this feature, the four standard bitwise operators ("~
3127       | & ^") are always numeric.  Adding a dot after each operator ("~. |.
3128       &. ^.") forces it to treat its operands as strings:
3129
3130           use experimental "bitwise";
3131           $foo =  150  |  105;        # yields 255  (0x96 | 0x69 is 0xFF)
3132           $foo = '150' |  105;        # yields 255
3133           $foo =  150  | '105';       # yields 255
3134           $foo = '150' | '105';       # yields 255
3135           $foo =  150  |. 105;        # yields string '155'
3136           $foo = '150' |. 105;        # yields string '155'
3137           $foo =  150  |.'105';       # yields string '155'
3138           $foo = '150' |.'105';       # yields string '155'
3139
3140           $baz = $foo &  $bar;        # both operands numeric
3141           $biz = $foo ^. $bar;        # both operands stringy
3142
3143       The assignment variants of these operators ("&= |= ^= &.= |.= ^.=")
3144       behave likewise under the feature.
3145
3146       The behavior of these operators is problematic (and subject to change)
3147       if either or both of the strings are encoded in UTF-8 (see "Byte and
3148       Character Semantics" in perlunicode.
3149
3150       See "vec" in perlfunc for information on how to manipulate individual
3151       bits in a bit vector.
3152
3153   Integer Arithmetic
3154       By default, Perl assumes that it must do most of its arithmetic in
3155       floating point.  But by saying
3156
3157           use integer;
3158
3159       you may tell the compiler to use integer operations (see integer for a
3160       detailed explanation) from here to the end of the enclosing BLOCK.  An
3161       inner BLOCK may countermand this by saying
3162
3163           no integer;
3164
3165       which lasts until the end of that BLOCK.  Note that this doesn't mean
3166       everything is an integer, merely that Perl will use integer operations
3167       for arithmetic, comparison, and bitwise operators.  For example, even
3168       under "use integer", if you take the sqrt(2), you'll still get
3169       1.4142135623731 or so.
3170
3171       Used on numbers, the bitwise operators ("&" "|" "^" "~" "<<" ">>")
3172       always produce integral results.  (But see also "Bitwise String
3173       Operators".)  However, "use integer" still has meaning for them.  By
3174       default, their results are interpreted as unsigned integers, but if
3175       "use integer" is in effect, their results are interpreted as signed
3176       integers.  For example, "~0" usually evaluates to a large integral
3177       value.  However, "use integer; ~0" is "-1" on two's-complement
3178       machines.
3179
3180   Floating-point Arithmetic
3181       While "use integer" provides integer-only arithmetic, there is no
3182       analogous mechanism to provide automatic rounding or truncation to a
3183       certain number of decimal places.  For rounding to a certain number of
3184       digits, "sprintf()" or "printf()" is usually the easiest route.  See
3185       perlfaq4.
3186
3187       Floating-point numbers are only approximations to what a mathematician
3188       would call real numbers.  There are infinitely more reals than floats,
3189       so some corners must be cut.  For example:
3190
3191           printf "%.20g\n", 123456789123456789;
3192           #        produces 123456789123456784
3193
3194       Testing for exact floating-point equality or inequality is not a good
3195       idea.  Here's a (relatively expensive) work-around to compare whether
3196       two floating-point numbers are equal to a particular number of decimal
3197       places.  See Knuth, volume II, for a more robust treatment of this
3198       topic.
3199
3200           sub fp_equal {
3201               my ($X, $Y, $POINTS) = @_;
3202               my ($tX, $tY);
3203               $tX = sprintf("%.${POINTS}g", $X);
3204               $tY = sprintf("%.${POINTS}g", $Y);
3205               return $tX eq $tY;
3206           }
3207
3208       The POSIX module (part of the standard perl distribution) implements
3209       "ceil()", "floor()", and other mathematical and trigonometric
3210       functions.  The "Math::Complex" module (part of the standard perl
3211       distribution) defines mathematical functions that work on both the
3212       reals and the imaginary numbers.  "Math::Complex" is not as efficient
3213       as POSIX, but POSIX can't work with complex numbers.
3214
3215       Rounding in financial applications can have serious implications, and
3216       the rounding method used should be specified precisely.  In these
3217       cases, it probably pays not to trust whichever system rounding is being
3218       used by Perl, but to instead implement the rounding function you need
3219       yourself.
3220
3221   Bigger Numbers
3222       The standard "Math::BigInt", "Math::BigRat", and "Math::BigFloat"
3223       modules, along with the "bignum", "bigint", and "bigrat" pragmas,
3224       provide variable-precision arithmetic and overloaded operators,
3225       although they're currently pretty slow.  At the cost of some space and
3226       considerable speed, they avoid the normal pitfalls associated with
3227       limited-precision representations.
3228
3229               use 5.010;
3230               use bigint;  # easy interface to Math::BigInt
3231               $x = 123456789123456789;
3232               say $x * $x;
3233           +15241578780673678515622620750190521
3234
3235       Or with rationals:
3236
3237               use 5.010;
3238               use bigrat;
3239               $x = 3/22;
3240               $y = 4/6;
3241               say "x/y is ", $x/$y;
3242               say "x*y is ", $x*$y;
3243               x/y is 9/44
3244               x*y is 1/11
3245
3246       Several modules let you calculate with unlimited or fixed precision
3247       (bound only by memory and CPU time).  There are also some non-standard
3248       modules that provide faster implementations via external C libraries.
3249
3250       Here is a short, but incomplete summary:
3251
3252         Math::String           treat string sequences like numbers
3253         Math::FixedPrecision   calculate with a fixed precision
3254         Math::Currency         for currency calculations
3255         Bit::Vector            manipulate bit vectors fast (uses C)
3256         Math::BigIntFast       Bit::Vector wrapper for big numbers
3257         Math::Pari             provides access to the Pari C library
3258         Math::Cephes           uses the external Cephes C library (no
3259                                big numbers)
3260         Math::Cephes::Fraction fractions via the Cephes library
3261         Math::GMP              another one using an external C library
3262         Math::GMPz             an alternative interface to libgmp's big ints
3263         Math::GMPq             an interface to libgmp's fraction numbers
3264         Math::GMPf             an interface to libgmp's floating point numbers
3265
3266       Choose wisely.
3267
3268
3269
3270perl v5.26.3                      2018-03-23                         PERLOP(1)
Impressum