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