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