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