This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
More detailed IO::Socket documentation
[perl5.git] / pod / perlop.pod
... / ...
CommitLineData
1=head1 NAME
2
3perlop - Perl operators and precedence
4
5=head1 SYNOPSIS
6
7Perl operators have the following associativity and precedence,
8listed from highest precedence to lowest. Note that all operators
9borrowed from C keep the same precedence relationship with each other,
10even where C's precedence is slightly screwy. (This makes learning
11Perl easier for C folks.) With very few exceptions, these all
12operate on scalar values only, not array values.
13
14 left terms and list operators (leftward)
15 left ->
16 nonassoc ++ --
17 right **
18 right ! ~ \ and unary + and -
19 left =~ !~
20 left * / % x
21 left + - .
22 left << >>
23 nonassoc named unary operators
24 nonassoc < > <= >= lt gt le ge
25 nonassoc == != <=> eq ne cmp
26 left &
27 left | ^
28 left &&
29 left ||
30 nonassoc .. ...
31 right ?:
32 right = += -= *= etc.
33 left , =>
34 nonassoc list operators (rightward)
35 right not
36 left and
37 left or xor
38
39In the following sections, these operators are covered in precedence order.
40
41=head1 DESCRIPTION
42
43=head2 Terms and List Operators (Leftward)
44
45A TERM has the highest precedence in Perl. They includes variables,
46quote and quote-like operators, any expression in parentheses,
47and any function whose arguments are parenthesized. Actually, there
48aren't really functions in this sense, just list operators and unary
49operators behaving as functions because you put parentheses around
50the arguments. These are all documented in L<perlfunc>.
51
52If any list operator (print(), etc.) or any unary operator (chdir(), etc.)
53is followed by a left parenthesis as the next token, the operator and
54arguments within parentheses are taken to be of highest precedence,
55just like a normal function call.
56
57In the absence of parentheses, the precedence of list operators such as
58C<print>, C<sort>, or C<chmod> is either very high or very low depending on
59whether you are looking at the left side or the right side of the operator.
60For example, in
61
62 @ary = (1, 3, sort 4, 2);
63 print @ary; # prints 1324
64
65the commas on the right of the sort are evaluated before the sort, but
66the commas on the left are evaluated after. In other words, list
67operators tend to gobble up all the arguments that follow them, and
68then act like a simple TERM with regard to the preceding expression.
69Note that you have to be careful with parentheses:
70
71 # These evaluate exit before doing the print:
72 print($foo, exit); # Obviously not what you want.
73 print $foo, exit; # Nor is this.
74
75 # These do the print before evaluating exit:
76 (print $foo), exit; # This is what you want.
77 print($foo), exit; # Or this.
78 print ($foo), exit; # Or even this.
79
80Also note that
81
82 print ($foo & 255) + 1, "\n";
83
84probably doesn't do what you expect at first glance. See
85L<Named Unary Operators> for more discussion of this.
86
87Also parsed as terms are the C<do {}> and C<eval {}> constructs, as
88well as subroutine and method calls, and the anonymous
89constructors C<[]> and C<{}>.
90
91See also L<Quote and Quote-like Operators> toward the end of this section,
92as well as L<"I/O Operators">.
93
94=head2 The Arrow Operator
95
96Just as in C and C++, "C<-E<gt>>" is an infix dereference operator. If the
97right side is either a C<[...]> or C<{...}> subscript, then the left side
98must be either a hard or symbolic reference to an array or hash (or
99a location capable of holding a hard reference, if it's an lvalue (assignable)).
100See L<perlref>.
101
102Otherwise, the right side is a method name or a simple scalar variable
103containing the method name, and the left side must either be an object
104(a blessed reference) or a class name (that is, a package name).
105See L<perlobj>.
106
107=head2 Auto-increment and Auto-decrement
108
109"++" and "--" work as in C. That is, if placed before a variable, they
110increment or decrement the variable before returning the value, and if
111placed after, increment or decrement the variable after returning the value.
112
113The auto-increment operator has a little extra builtin magic to it. If
114you increment a variable that is numeric, or that has ever been used in
115a numeric context, you get a normal increment. If, however, the
116variable has been used in only string contexts since it was set, and
117has a value that is not null and matches the pattern
118C</^[a-zA-Z]*[0-9]*$/>, the increment is done as a string, preserving each
119character within its range, with carry:
120
121 print ++($foo = '99'); # prints '100'
122 print ++($foo = 'a0'); # prints 'a1'
123 print ++($foo = 'Az'); # prints 'Ba'
124 print ++($foo = 'zz'); # prints 'aaa'
125
126The auto-decrement operator is not magical.
127
128=head2 Exponentiation
129
130Binary "**" is the exponentiation operator. Note that it binds even more
131tightly than unary minus, so -2**4 is -(2**4), not (-2)**4. (This is
132implemented using C's pow(3) function, which actually works on doubles
133internally.)
134
135=head2 Symbolic Unary Operators
136
137Unary "!" performs logical negation, i.e., "not". See also C<not> for a lower
138precedence version of this.
139
140Unary "-" performs arithmetic negation if the operand is numeric. If
141the operand is an identifier, a string consisting of a minus sign
142concatenated with the identifier is returned. Otherwise, if the string
143starts with a plus or minus, a string starting with the opposite sign
144is returned. One effect of these rules is that C<-bareword> is equivalent
145to C<"-bareword">.
146
147Unary "~" performs bitwise negation, i.e., 1's complement.
148(See also L<Integer Arithmetic>.)
149
150Unary "+" has no effect whatsoever, even on strings. It is useful
151syntactically for separating a function name from a parenthesized expression
152that would otherwise be interpreted as the complete list of function
153arguments. (See examples above under L<Terms and List Operators (Leftward)>.)
154
155Unary "\" creates a reference to whatever follows it. See L<perlref>.
156Do not confuse this behavior with the behavior of backslash within a
157string, although both forms do convey the notion of protecting the next
158thing from interpretation.
159
160=head2 Binding Operators
161
162Binary "=~" binds a scalar expression to a pattern match. Certain operations
163search or modify the string $_ by default. This operator makes that kind
164of operation work on some other string. The right argument is a search
165pattern, substitution, or translation. The left argument is what is
166supposed to be searched, substituted, or translated instead of the default
167$_. The return value indicates the success of the operation. (If the
168right argument is an expression rather than a search pattern,
169substitution, or translation, it is interpreted as a search pattern at run
170time. This can be is less efficient than an explicit search, because the
171pattern must be compiled every time the expression is evaluated.
172
173Binary "!~" is just like "=~" except the return value is negated in
174the logical sense.
175
176=head2 Multiplicative Operators
177
178Binary "*" multiplies two numbers.
179
180Binary "/" divides two numbers.
181
182Binary "%" computes the modulus of two numbers. Given integer
183operands C<$a> and C<$b>: If C<$b> is positive, then C<$a % $b> is
184C<$a> minus the largest multiple of C<$b> that is not greater than
185C<$a>. If C<$b> is negative, then C<$a % $b> is C<$a> minus the
186smallest multiple of C<$b> that is not less than C<$a> (i.e. the
187result will be less than or equal to zero).
188
189Binary "x" is the repetition operator. In a scalar context, it
190returns a string consisting of the left operand repeated the number of
191times specified by the right operand. In a list context, if the left
192operand is a list in parentheses, it repeats the list.
193
194 print '-' x 80; # print row of dashes
195
196 print "\t" x ($tab/8), ' ' x ($tab%8); # tab over
197
198 @ones = (1) x 80; # a list of 80 1's
199 @ones = (5) x @ones; # set all elements to 5
200
201
202=head2 Additive Operators
203
204Binary "+" returns the sum of two numbers.
205
206Binary "-" returns the difference of two numbers.
207
208Binary "." concatenates two strings.
209
210=head2 Shift Operators
211
212Binary "<<" returns the value of its left argument shifted left by the
213number of bits specified by the right argument. Arguments should be
214integers. (See also L<Integer Arithmetic>.)
215
216Binary ">>" returns the value of its left argument shifted right by
217the number of bits specified by the right argument. Arguments should
218be integers. (See also L<Integer Arithmetic>.)
219
220=head2 Named Unary Operators
221
222The various named unary operators are treated as functions with one
223argument, with optional parentheses. These include the filetest
224operators, like C<-f>, C<-M>, etc. See L<perlfunc>.
225
226If any list operator (print(), etc.) or any unary operator (chdir(), etc.)
227is followed by a left parenthesis as the next token, the operator and
228arguments within parentheses are taken to be of highest precedence,
229just like a normal function call. Examples:
230
231 chdir $foo || die; # (chdir $foo) || die
232 chdir($foo) || die; # (chdir $foo) || die
233 chdir ($foo) || die; # (chdir $foo) || die
234 chdir +($foo) || die; # (chdir $foo) || die
235
236but, because * is higher precedence than ||:
237
238 chdir $foo * 20; # chdir ($foo * 20)
239 chdir($foo) * 20; # (chdir $foo) * 20
240 chdir ($foo) * 20; # (chdir $foo) * 20
241 chdir +($foo) * 20; # chdir ($foo * 20)
242
243 rand 10 * 20; # rand (10 * 20)
244 rand(10) * 20; # (rand 10) * 20
245 rand (10) * 20; # (rand 10) * 20
246 rand +(10) * 20; # rand (10 * 20)
247
248See also L<"Terms and List Operators (Leftward)">.
249
250=head2 Relational Operators
251
252Binary "E<lt>" returns true if the left argument is numerically less than
253the right argument.
254
255Binary "E<gt>" returns true if the left argument is numerically greater
256than the right argument.
257
258Binary "E<lt>=" returns true if the left argument is numerically less than
259or equal to the right argument.
260
261Binary "E<gt>=" returns true if the left argument is numerically greater
262than or equal to the right argument.
263
264Binary "lt" returns true if the left argument is stringwise less than
265the right argument.
266
267Binary "gt" returns true if the left argument is stringwise greater
268than the right argument.
269
270Binary "le" returns true if the left argument is stringwise less than
271or equal to the right argument.
272
273Binary "ge" returns true if the left argument is stringwise greater
274than or equal to the right argument.
275
276=head2 Equality Operators
277
278Binary "==" returns true if the left argument is numerically equal to
279the right argument.
280
281Binary "!=" returns true if the left argument is numerically not equal
282to the right argument.
283
284Binary "E<lt>=E<gt>" returns -1, 0, or 1 depending on whether the left
285argument is numerically less than, equal to, or greater than the right
286argument.
287
288Binary "eq" returns true if the left argument is stringwise equal to
289the right argument.
290
291Binary "ne" returns true if the left argument is stringwise not equal
292to the right argument.
293
294Binary "cmp" returns -1, 0, or 1 depending on whether the left argument is stringwise
295less than, equal to, or greater than the right argument.
296
297"lt", "le", "ge", "gt" and "cmp" use the collation (sort) order specified
298by the current locale if C<use locale> is in effect. See L<perllocale>.
299
300=head2 Bitwise And
301
302Binary "&" returns its operators ANDed together bit by bit.
303(See also L<Integer Arithmetic>.)
304
305=head2 Bitwise Or and Exclusive Or
306
307Binary "|" returns its operators ORed together bit by bit.
308(See also L<Integer Arithmetic>.)
309
310Binary "^" returns its operators XORed together bit by bit.
311(See also L<Integer Arithmetic>.)
312
313=head2 C-style Logical And
314
315Binary "&&" performs a short-circuit logical AND operation. That is,
316if the left operand is false, the right operand is not even evaluated.
317Scalar or list context propagates down to the right operand if it
318is evaluated.
319
320=head2 C-style Logical Or
321
322Binary "||" performs a short-circuit logical OR operation. That is,
323if the left operand is true, the right operand is not even evaluated.
324Scalar or list context propagates down to the right operand if it
325is evaluated.
326
327The C<||> and C<&&> operators differ from C's in that, rather than returning
3280 or 1, they return the last value evaluated. Thus, a reasonably portable
329way to find out the home directory (assuming it's not "0") might be:
330
331 $home = $ENV{'HOME'} || $ENV{'LOGDIR'} ||
332 (getpwuid($<))[7] || die "You're homeless!\n";
333
334As more readable alternatives to C<&&> and C<||>, Perl provides "and" and
335"or" operators (see below). The short-circuit behavior is identical. The
336precedence of "and" and "or" is much lower, however, so that you can
337safely use them after a list operator without the need for
338parentheses:
339
340 unlink "alpha", "beta", "gamma"
341 or gripe(), next LINE;
342
343With the C-style operators that would have been written like this:
344
345 unlink("alpha", "beta", "gamma")
346 || (gripe(), next LINE);
347
348=head2 Range Operator
349
350Binary ".." is the range operator, which is really two different
351operators depending on the context. In a list context, it returns an
352array of values counting (by ones) from the left value to the right
353value. This is useful for writing C<for (1..10)> loops and for doing
354slice operations on arrays. Be aware that under the current implementation,
355a temporary array is created, so you'll burn a lot of memory if you
356write something like this:
357
358 for (1 .. 1_000_000) {
359 # code
360 }
361
362In a scalar context, ".." returns a boolean value. The operator is
363bistable, like a flip-flop, and emulates the line-range (comma) operator
364of B<sed>, B<awk>, and various editors. Each ".." operator maintains its
365own boolean state. It is false as long as its left operand is false.
366Once the left operand is true, the range operator stays true until the
367right operand is true, I<AFTER> which the range operator becomes false
368again. (It doesn't become false till the next time the range operator is
369evaluated. It can test the right operand and become false on the same
370evaluation it became true (as in B<awk>), but it still returns true once.
371If you don't want it to test the right operand till the next evaluation
372(as in B<sed>), use three dots ("...") instead of two.) The right
373operand is not evaluated while the operator is in the "false" state, and
374the left operand is not evaluated while the operator is in the "true"
375state. The precedence is a little lower than || and &&. The value
376returned is either the null string for false, or a sequence number
377(beginning with 1) for true. The sequence number is reset for each range
378encountered. The final sequence number in a range has the string "E0"
379appended to it, which doesn't affect its numeric value, but gives you
380something to search for if you want to exclude the endpoint. You can
381exclude the beginning point by waiting for the sequence number to be
382greater than 1. If either operand of scalar ".." is a numeric literal,
383that operand is implicitly compared to the C<$.> variable, the current
384line number. Examples:
385
386As a scalar operator:
387
388 if (101 .. 200) { print; } # print 2nd hundred lines
389 next line if (1 .. /^$/); # skip header lines
390 s/^/> / if (/^$/ .. eof()); # quote body
391
392As a list operator:
393
394 for (101 .. 200) { print; } # print $_ 100 times
395 @foo = @foo[$[ .. $#foo]; # an expensive no-op
396 @foo = @foo[$#foo-4 .. $#foo]; # slice last 5 items
397
398The range operator (in a list context) makes use of the magical
399auto-increment algorithm if the operands are strings. You
400can say
401
402 @alphabet = ('A' .. 'Z');
403
404to get all the letters of the alphabet, or
405
406 $hexdigit = (0 .. 9, 'a' .. 'f')[$num & 15];
407
408to get a hexadecimal digit, or
409
410 @z2 = ('01' .. '31'); print $z2[$mday];
411
412to get dates with leading zeros. If the final value specified is not
413in the sequence that the magical increment would produce, the sequence
414goes until the next value would be longer than the final value
415specified.
416
417=head2 Conditional Operator
418
419Ternary "?:" is the conditional operator, just as in C. It works much
420like an if-then-else. If the argument before the ? is true, the
421argument before the : is returned, otherwise the argument after the :
422is returned. For example:
423
424 printf "I have %d dog%s.\n", $n,
425 ($n == 1) ? '' : "s";
426
427Scalar or list context propagates downward into the 2nd
428or 3rd argument, whichever is selected.
429
430 $a = $ok ? $b : $c; # get a scalar
431 @a = $ok ? @b : @c; # get an array
432 $a = $ok ? @b : @c; # oops, that's just a count!
433
434The operator may be assigned to if both the 2nd and 3rd arguments are
435legal lvalues (meaning that you can assign to them):
436
437 ($a_or_b ? $a : $b) = $c;
438
439This is not necessarily guaranteed to contribute to the readability of your program.
440
441=head2 Assignment Operators
442
443"=" is the ordinary assignment operator.
444
445Assignment operators work as in C. That is,
446
447 $a += 2;
448
449is equivalent to
450
451 $a = $a + 2;
452
453although without duplicating any side effects that dereferencing the lvalue
454might trigger, such as from tie(). Other assignment operators work similarly.
455The following are recognized:
456
457 **= += *= &= <<= &&=
458 -= /= |= >>= ||=
459 .= %= ^=
460 x=
461
462Note that while these are grouped by family, they all have the precedence
463of assignment.
464
465Unlike in C, the assignment operator produces a valid lvalue. Modifying
466an assignment is equivalent to doing the assignment and then modifying
467the variable that was assigned to. This is useful for modifying
468a copy of something, like this:
469
470 ($tmp = $global) =~ tr [A-Z] [a-z];
471
472Likewise,
473
474 ($a += 2) *= 3;
475
476is equivalent to
477
478 $a += 2;
479 $a *= 3;
480
481=head2 Comma Operator
482
483Binary "," is the comma operator. In a scalar context it evaluates
484its left argument, throws that value away, then evaluates its right
485argument and returns that value. This is just like C's comma operator.
486
487In a list context, it's just the list argument separator, and inserts
488both its arguments into the list.
489
490The =E<gt> digraph is mostly just a synonym for the comma operator. It's useful for
491documenting arguments that come in pairs. As of release 5.001, it also forces
492any word to the left of it to be interpreted as a string.
493
494=head2 List Operators (Rightward)
495
496On the right side of a list operator, it has very low precedence,
497such that it controls all comma-separated expressions found there.
498The only operators with lower precedence are the logical operators
499"and", "or", and "not", which may be used to evaluate calls to list
500operators without the need for extra parentheses:
501
502 open HANDLE, "filename"
503 or die "Can't open: $!\n";
504
505See also discussion of list operators in L<Terms and List Operators (Leftward)>.
506
507=head2 Logical Not
508
509Unary "not" returns the logical negation of the expression to its right.
510It's the equivalent of "!" except for the very low precedence.
511
512=head2 Logical And
513
514Binary "and" returns the logical conjunction of the two surrounding
515expressions. It's equivalent to && except for the very low
516precedence. This means that it short-circuits: i.e., the right
517expression is evaluated only if the left expression is true.
518
519=head2 Logical or and Exclusive Or
520
521Binary "or" returns the logical disjunction of the two surrounding
522expressions. It's equivalent to || except for the very low
523precedence. This means that it short-circuits: i.e., the right
524expression is evaluated only if the left expression is false.
525
526Binary "xor" returns the exclusive-OR of the two surrounding expressions.
527It cannot short circuit, of course.
528
529=head2 C Operators Missing From Perl
530
531Here is what C has that Perl doesn't:
532
533=over 8
534
535=item unary &
536
537Address-of operator. (But see the "\" operator for taking a reference.)
538
539=item unary *
540
541Dereference-address operator. (Perl's prefix dereferencing
542operators are typed: $, @, %, and &.)
543
544=item (TYPE)
545
546Type casting operator.
547
548=back
549
550=head2 Quote and Quote-like Operators
551
552While we usually think of quotes as literal values, in Perl they
553function as operators, providing various kinds of interpolating and
554pattern matching capabilities. Perl provides customary quote characters
555for these behaviors, but also provides a way for you to choose your
556quote character for any of them. In the following table, a C<{}> represents
557any pair of delimiters you choose. Non-bracketing delimiters use
558the same character fore and aft, but the 4 sorts of brackets
559(round, angle, square, curly) will all nest.
560
561 Customary Generic Meaning Interpolates
562 '' q{} Literal no
563 "" qq{} Literal yes
564 `` qx{} Command yes
565 qw{} Word list no
566 // m{} Pattern match yes
567 s{}{} Substitution yes
568 tr{}{} Translation no
569
570For constructs that do interpolation, variables beginning with "C<$>" or "C<@>"
571are interpolated, as are the following sequences:
572
573 \t tab (HT, TAB)
574 \n newline (LF, NL)
575 \r return (CR)
576 \f form feed (FF)
577 \b backspace (BS)
578 \a alarm (bell) (BEL)
579 \e escape (ESC)
580 \033 octal char
581 \x1b hex char
582 \c[ control char
583 \l lowercase next char
584 \u uppercase next char
585 \L lowercase till \E
586 \U uppercase till \E
587 \E end case modification
588 \Q quote regexp metacharacters till \E
589
590If C<use locale> is in effect, the case map used by C<\l>, C<\L>, C<\u>
591and <\U> is taken from the current locale. See L<perllocale>.
592
593Patterns are subject to an additional level of interpretation as a
594regular expression. This is done as a second pass, after variables are
595interpolated, so that regular expressions may be incorporated into the
596pattern from the variables. If this is not what you want, use C<\Q> to
597interpolate a variable literally.
598
599Apart from the above, there are no multiple levels of interpolation. In
600particular, contrary to the expectations of shell programmers, back-quotes
601do I<NOT> interpolate within double quotes, nor do single quotes impede
602evaluation of variables when used within double quotes.
603
604=head2 Regexp Quote-Like Operators
605
606Here are the quote-like operators that apply to pattern
607matching and related activities.
608
609=over 8
610
611=item ?PATTERN?
612
613This is just like the C</pattern/> search, except that it matches only
614once between calls to the reset() operator. This is a useful
615optimization when you want to see only the first occurrence of
616something in each file of a set of files, for instance. Only C<??>
617patterns local to the current package are reset.
618
619This usage is vaguely deprecated, and may be removed in some future
620version of Perl.
621
622=item m/PATTERN/gimosx
623
624=item /PATTERN/gimosx
625
626Searches a string for a pattern match, and in a scalar context returns
627true (1) or false (''). If no string is specified via the C<=~> or
628C<!~> operator, the $_ string is searched. (The string specified with
629C<=~> need not be an lvalue--it may be the result of an expression
630evaluation, but remember the C<=~> binds rather tightly.) See also
631L<perlre>.
632See L<perllocale> for discussion of additional considerations which apply
633when C<use locale> is in effect.
634
635Options are:
636
637 g Match globally, i.e., find all occurrences.
638 i Do case-insensitive pattern matching.
639 m Treat string as multiple lines.
640 o Compile pattern only once.
641 s Treat string as single line.
642 x Use extended regular expressions.
643
644If "/" is the delimiter then the initial C<m> is optional. With the C<m>
645you can use any pair of non-alphanumeric, non-whitespace characters as
646delimiters. This is particularly useful for matching Unix path names
647that contain "/", to avoid LTS (leaning toothpick syndrome). If "?" is
648the delimiter, then the match-only-once rule of C<?PATTERN?> applies.
649
650PATTERN may contain variables, which will be interpolated (and the
651pattern recompiled) every time the pattern search is evaluated. (Note
652that C<$)> and C<$|> might not be interpolated because they look like
653end-of-string tests.) If you want such a pattern to be compiled only
654once, add a C</o> after the trailing delimiter. This avoids expensive
655run-time recompilations, and is useful when the value you are
656interpolating won't change over the life of the script. However, mentioning
657C</o> constitutes a promise that you won't change the variables in the pattern.
658If you change them, Perl won't even notice.
659
660If the PATTERN evaluates to a null string, the last
661successfully executed regular expression is used instead.
662
663If used in a context that requires a list value, a pattern match returns a
664list consisting of the subexpressions matched by the parentheses in the
665pattern, i.e., (C<$1>, $2, $3...). (Note that here $1 etc. are also set, and
666that this differs from Perl 4's behavior.) If the match fails, a null
667array is returned. If the match succeeds, but there were no parentheses,
668a list value of (1) is returned.
669
670Examples:
671
672 open(TTY, '/dev/tty');
673 <TTY> =~ /^y/i && foo(); # do foo if desired
674
675 if (/Version: *([0-9.]*)/) { $version = $1; }
676
677 next if m#^/usr/spool/uucp#;
678
679 # poor man's grep
680 $arg = shift;
681 while (<>) {
682 print if /$arg/o; # compile only once
683 }
684
685 if (($F1, $F2, $Etc) = ($foo =~ /^(\S+)\s+(\S+)\s*(.*)/))
686
687This last example splits $foo into the first two words and the
688remainder of the line, and assigns those three fields to $F1, $F2, and
689$Etc. The conditional is true if any variables were assigned, i.e., if
690the pattern matched.
691
692The C</g> modifier specifies global pattern matching--that is, matching
693as many times as possible within the string. How it behaves depends on
694the context. In a list context, it returns a list of all the
695substrings matched by all the parentheses in the regular expression.
696If there are no parentheses, it returns a list of all the matched
697strings, as if there were parentheses around the whole pattern.
698
699In a scalar context, C<m//g> iterates through the string, returning TRUE
700each time it matches, and FALSE when it eventually runs out of
701matches. (In other words, it remembers where it left off last time and
702restarts the search at that point. You can actually find the current
703match position of a string or set it using the pos() function--see
704L<perlfunc/pos>.) Note that you can use this feature to stack C<m//g>
705matches or intermix C<m//g> matches with C<m/\G.../g>. Note that
706the C<\G> zero-width assertion is not supported without the C</g>
707modifier; currently, without C</g>, C<\G> behaves just like C<\A>, but
708that's accidental and may change in the future.
709
710If you modify the string in any way, the match position is reset to the
711beginning. Examples:
712
713 # list context
714 ($one,$five,$fifteen) = (`uptime` =~ /(\d+\.\d+)/g);
715
716 # scalar context
717 $/ = ""; $* = 1; # $* deprecated in modern perls
718 while (defined($paragraph = <>)) {
719 while ($paragraph =~ /[a-z]['")]*[.!?]+['")]*\s/g) {
720 $sentences++;
721 }
722 }
723 print "$sentences\n";
724
725 # using m//g with \G
726 $_ = "ppooqppqq";
727 while ($i++ < 2) {
728 print "1: '";
729 print $1 while /(o)/g; print "', pos=", pos, "\n";
730 print "2: '";
731 print $1 if /\G(q)/g; print "', pos=", pos, "\n";
732 print "3: '";
733 print $1 while /(p)/g; print "', pos=", pos, "\n";
734 }
735
736The last example should print:
737
738 1: 'oo', pos=4
739 2: 'q', pos=5
740 3: 'pp', pos=7
741 1: '', pos=7
742 2: 'q', pos=8
743 3: '', pos=8
744
745A useful idiom for C<lex>-like scanners is C</\G.../g>. You can
746combine several regexps like this to process a string part-by-part,
747doing different actions depending on which regexp matched. The next
748regexp would step in at the place the previous one left off.
749
750 $_ = <<'EOL';
751 $url = new URI::URL "http://www/"; die if $url eq "xXx";
752 EOL
753 LOOP:
754 {
755 print(" digits"), redo LOOP if /\G\d+\b[,.;]?\s*/g;
756 print(" lowercase"), redo LOOP if /\G[a-z]+\b[,.;]?\s*/g;
757 print(" UPPERCASE"), redo LOOP if /\G[A-Z]+\b[,.;]?\s*/g;
758 print(" Capitalized"), redo LOOP if /\G[A-Z][a-z]+\b[,.;]?\s*/g;
759 print(" MiXeD"), redo LOOP if /\G[A-Za-z]+\b[,.;]?\s*/g;
760 print(" alphanumeric"), redo LOOP if /\G[A-Za-z0-9]+\b[,.;]?\s*/g;
761 print(" line-noise"), redo LOOP if /\G[^A-Za-z0-9]+/g;
762 print ". That's all!\n";
763 }
764
765Here is the output (split into several lines):
766
767 line-noise lowercase line-noise lowercase UPPERCASE line-noise
768 UPPERCASE line-noise lowercase line-noise lowercase line-noise
769 lowercase lowercase line-noise lowercase lowercase line-noise
770 MiXeD line-noise. That's all!
771
772=item q/STRING/
773
774=item C<'STRING'>
775
776A single-quoted, literal string. A backslash represents a backslash
777unless followed by the delimiter or another backslash, in which case
778the delimiter or backslash is interpolated.
779
780 $foo = q!I said, "You said, 'She said it.'"!;
781 $bar = q('This is it.');
782 $baz = '\n'; # a two-character string
783
784=item qq/STRING/
785
786=item "STRING"
787
788A double-quoted, interpolated string.
789
790 $_ .= qq
791 (*** The previous line contains the naughty word "$1".\n)
792 if /(tcl|rexx|python)/; # :-)
793 $baz = "\n"; # a one-character string
794
795=item qx/STRING/
796
797=item `STRING`
798
799A string which is interpolated and then executed as a system command.
800The collected standard output of the command is returned. In scalar
801context, it comes back as a single (potentially multi-line) string.
802In list context, returns a list of lines (however you've defined lines
803with $/ or $INPUT_RECORD_SEPARATOR).
804
805 $today = qx{ date };
806
807See L<"I/O Operators"> for more discussion.
808
809=item qw/STRING/
810
811Returns a list of the words extracted out of STRING, using embedded
812whitespace as the word delimiters. It is exactly equivalent to
813
814 split(' ', q/STRING/);
815
816Some frequently seen examples:
817
818 use POSIX qw( setlocale localeconv )
819 @EXPORT = qw( foo bar baz );
820
821A common mistake is to try to separate the words with comma or to put
822comments into a multi-line qw-string. For this reason the C<-w>
823switch produce warnings if the STRING contains the "," or the "#"
824character.
825
826=item s/PATTERN/REPLACEMENT/egimosx
827
828Searches a string for a pattern, and if found, replaces that pattern
829with the replacement text and returns the number of substitutions
830made. Otherwise it returns false (specifically, the empty string).
831
832If no string is specified via the C<=~> or C<!~> operator, the C<$_>
833variable is searched and modified. (The string specified with C<=~> must
834be a scalar variable, an array element, a hash element, or an assignment
835to one of those, i.e., an lvalue.)
836
837If the delimiter chosen is single quote, no variable interpolation is
838done on either the PATTERN or the REPLACEMENT. Otherwise, if the
839PATTERN contains a $ that looks like a variable rather than an
840end-of-string test, the variable will be interpolated into the pattern
841at run-time. If you want the pattern compiled only once the first time
842the variable is interpolated, use the C</o> option. If the pattern
843evaluates to a null string, the last successfully executed regular
844expression is used instead. See L<perlre> for further explanation on these.
845See L<perllocale> for discussion of additional considerations which apply
846when C<use locale> is in effect.
847
848Options are:
849
850 e Evaluate the right side as an expression.
851 g Replace globally, i.e., all occurrences.
852 i Do case-insensitive pattern matching.
853 m Treat string as multiple lines.
854 o Compile pattern only once.
855 s Treat string as single line.
856 x Use extended regular expressions.
857
858Any non-alphanumeric, non-whitespace delimiter may replace the
859slashes. If single quotes are used, no interpretation is done on the
860replacement string (the C</e> modifier overrides this, however). Unlike
861Perl 4, Perl 5 treats backticks as normal delimiters; the replacement
862text is not evaluated as a command. If the
863PATTERN is delimited by bracketing quotes, the REPLACEMENT has its own
864pair of quotes, which may or may not be bracketing quotes, e.g.,
865C<s(foo)(bar)> or C<sE<lt>fooE<gt>/bar/>. A C</e> will cause the
866replacement portion to be interpreter as a full-fledged Perl expression
867and eval()ed right then and there. It is, however, syntax checked at
868compile-time.
869
870Examples:
871
872 s/\bgreen\b/mauve/g; # don't change wintergreen
873
874 $path =~ s|/usr/bin|/usr/local/bin|;
875
876 s/Login: $foo/Login: $bar/; # run-time pattern
877
878 ($foo = $bar) =~ s/this/that/;
879
880 $count = ($paragraph =~ s/Mister\b/Mr./g);
881
882 $_ = 'abc123xyz';
883 s/\d+/$&*2/e; # yields 'abc246xyz'
884 s/\d+/sprintf("%5d",$&)/e; # yields 'abc 246xyz'
885 s/\w/$& x 2/eg; # yields 'aabbcc 224466xxyyzz'
886
887 s/%(.)/$percent{$1}/g; # change percent escapes; no /e
888 s/%(.)/$percent{$1} || $&/ge; # expr now, so /e
889 s/^=(\w+)/&pod($1)/ge; # use function call
890
891 # /e's can even nest; this will expand
892 # simple embedded variables in $_
893 s/(\$\w+)/$1/eeg;
894
895 # Delete C comments.
896 $program =~ s {
897 /\* # Match the opening delimiter.
898 .*? # Match a minimal number of characters.
899 \*/ # Match the closing delimiter.
900 } []gsx;
901
902 s/^\s*(.*?)\s*$/$1/; # trim white space
903
904 s/([^ ]*) *([^ ]*)/$2 $1/; # reverse 1st two fields
905
906Note the use of $ instead of \ in the last example. Unlike
907B<sed>, we use the \E<lt>I<digit>E<gt> form in only the left hand side.
908Anywhere else it's $E<lt>I<digit>E<gt>.
909
910Occasionally, you can't use just a C</g> to get all the changes
911to occur. Here are two common cases:
912
913 # put commas in the right places in an integer
914 1 while s/(.*\d)(\d\d\d)/$1,$2/g; # perl4
915 1 while s/(\d)(\d\d\d)(?!\d)/$1,$2/g; # perl5
916
917 # expand tabs to 8-column spacing
918 1 while s/\t+/' ' x (length($&)*8 - length($`)%8)/e;
919
920
921=item tr/SEARCHLIST/REPLACEMENTLIST/cds
922
923=item y/SEARCHLIST/REPLACEMENTLIST/cds
924
925Translates all occurrences of the characters found in the search list
926with the corresponding character in the replacement list. It returns
927the number of characters replaced or deleted. If no string is
928specified via the =~ or !~ operator, the $_ string is translated. (The
929string specified with =~ must be a scalar variable, an array element, a
930hash element, or an assignment to one of those, i.e., an lvalue.)
931For B<sed> devotees, C<y> is provided as a synonym for C<tr>. If the
932SEARCHLIST is delimited by bracketing quotes, the REPLACEMENTLIST has
933its own pair of quotes, which may or may not be bracketing quotes,
934e.g., C<tr[A-Z][a-z]> or C<tr(+-*/)/ABCD/>.
935
936Options:
937
938 c Complement the SEARCHLIST.
939 d Delete found but unreplaced characters.
940 s Squash duplicate replaced characters.
941
942If the C</c> modifier is specified, the SEARCHLIST character set is
943complemented. If the C</d> modifier is specified, any characters specified
944by SEARCHLIST not found in REPLACEMENTLIST are deleted. (Note
945that this is slightly more flexible than the behavior of some B<tr>
946programs, which delete anything they find in the SEARCHLIST, period.)
947If the C</s> modifier is specified, sequences of characters that were
948translated to the same character are squashed down to a single instance of the
949character.
950
951If the C</d> modifier is used, the REPLACEMENTLIST is always interpreted
952exactly as specified. Otherwise, if the REPLACEMENTLIST is shorter
953than the SEARCHLIST, the final character is replicated till it is long
954enough. If the REPLACEMENTLIST is null, the SEARCHLIST is replicated.
955This latter is useful for counting characters in a class or for
956squashing character sequences in a class.
957
958Examples:
959
960 $ARGV[1] =~ tr/A-Z/a-z/; # canonicalize to lower case
961
962 $cnt = tr/*/*/; # count the stars in $_
963
964 $cnt = $sky =~ tr/*/*/; # count the stars in $sky
965
966 $cnt = tr/0-9//; # count the digits in $_
967
968 tr/a-zA-Z//s; # bookkeeper -> bokeper
969
970 ($HOST = $host) =~ tr/a-z/A-Z/;
971
972 tr/a-zA-Z/ /cs; # change non-alphas to single space
973
974 tr [\200-\377]
975 [\000-\177]; # delete 8th bit
976
977If multiple translations are given for a character, only the first one is used:
978
979 tr/AAA/XYZ/
980
981will translate any A to X.
982
983Note that because the translation table is built at compile time, neither
984the SEARCHLIST nor the REPLACEMENTLIST are subjected to double quote
985interpolation. That means that if you want to use variables, you must use
986an eval():
987
988 eval "tr/$oldlist/$newlist/";
989 die $@ if $@;
990
991 eval "tr/$oldlist/$newlist/, 1" or die $@;
992
993=back
994
995=head2 I/O Operators
996
997There are several I/O operators you should know about.
998A string is enclosed by backticks (grave accents) first undergoes
999variable substitution just like a double quoted string. It is then
1000interpreted as a command, and the output of that command is the value
1001of the pseudo-literal, like in a shell. In a scalar context, a single
1002string consisting of all the output is returned. In a list context,
1003a list of values is returned, one for each line of output. (You can
1004set C<$/> to use a different line terminator.) The command is executed
1005each time the pseudo-literal is evaluated. The status value of the
1006command is returned in C<$?> (see L<perlvar> for the interpretation
1007of C<$?>). Unlike in B<csh>, no translation is done on the return
1008data--newlines remain newlines. Unlike in any of the shells, single
1009quotes do not hide variable names in the command from interpretation.
1010To pass a $ through to the shell you need to hide it with a backslash.
1011The generalized form of backticks is C<qx//>. (Because backticks
1012always undergo shell expansion as well, see L<perlsec> for
1013security concerns.)
1014
1015Evaluating a filehandle in angle brackets yields the next line from
1016that file (newline, if any, included), or C<undef> at end of file.
1017Ordinarily you must assign that value to a variable, but there is one
1018situation where an automatic assignment happens. I<If and ONLY if> the
1019input symbol is the only thing inside the conditional of a C<while> or
1020C<for(;;)> loop, the value is automatically assigned to the variable
1021C<$_>. The assigned value is then tested to see if it is defined.
1022(This may seem like an odd thing to you, but you'll use the construct
1023in almost every Perl script you write.) Anyway, the following lines
1024are equivalent to each other:
1025
1026 while (defined($_ = <STDIN>)) { print; }
1027 while (<STDIN>) { print; }
1028 for (;<STDIN>;) { print; }
1029 print while defined($_ = <STDIN>);
1030 print while <STDIN>;
1031
1032The filehandles STDIN, STDOUT, and STDERR are predefined. (The
1033filehandles C<stdin>, C<stdout>, and C<stderr> will also work except in
1034packages, where they would be interpreted as local identifiers rather
1035than global.) Additional filehandles may be created with the open()
1036function. See L<perlfunc/open()> for details on this.
1037
1038If a E<lt>FILEHANDLEE<gt> is used in a context that is looking for a list, a
1039list consisting of all the input lines is returned, one line per list
1040element. It's easy to make a I<LARGE> data space this way, so use with
1041care.
1042
1043The null filehandle E<lt>E<gt> is special and can be used to emulate the
1044behavior of B<sed> and B<awk>. Input from E<lt>E<gt> comes either from
1045standard input, or from each file listed on the command line. Here's
1046how it works: the first time E<lt>E<gt> is evaluated, the @ARGV array is
1047checked, and if it is null, C<$ARGV[0]> is set to "-", which when opened
1048gives you standard input. The @ARGV array is then processed as a list
1049of filenames. The loop
1050
1051 while (<>) {
1052 ... # code for each line
1053 }
1054
1055is equivalent to the following Perl-like pseudo code:
1056
1057 unshift(@ARGV, '-') if $#ARGV < $[;
1058 while ($ARGV = shift) {
1059 open(ARGV, $ARGV);
1060 while (<ARGV>) {
1061 ... # code for each line
1062 }
1063 }
1064
1065except that it isn't so cumbersome to say, and will actually work. It
1066really does shift array @ARGV and put the current filename into variable
1067$ARGV. It also uses filehandle I<ARGV> internally--E<lt>E<gt> is just a
1068synonym for E<lt>ARGVE<gt>, which is magical. (The pseudo code above
1069doesn't work because it treats E<lt>ARGVE<gt> as non-magical.)
1070
1071You can modify @ARGV before the first E<lt>E<gt> as long as the array ends up
1072containing the list of filenames you really want. Line numbers (C<$.>)
1073continue as if the input were one big happy file. (But see example
1074under eof() for how to reset line numbers on each file.)
1075
1076If you want to set @ARGV to your own list of files, go right ahead. If
1077you want to pass switches into your script, you can use one of the
1078Getopts modules or put a loop on the front like this:
1079
1080 while ($_ = $ARGV[0], /^-/) {
1081 shift;
1082 last if /^--$/;
1083 if (/^-D(.*)/) { $debug = $1 }
1084 if (/^-v/) { $verbose++ }
1085 ... # other switches
1086 }
1087 while (<>) {
1088 ... # code for each line
1089 }
1090
1091The E<lt>E<gt> symbol will return FALSE only once. If you call it again after
1092this it will assume you are processing another @ARGV list, and if you
1093haven't set @ARGV, will input from STDIN.
1094
1095If the string inside the angle brackets is a reference to a scalar
1096variable (e.g., E<lt>$fooE<gt>), then that variable contains the name of the
1097filehandle to input from, or a reference to the same. For example:
1098
1099 $fh = \*STDIN;
1100 $line = <$fh>;
1101
1102If the string inside angle brackets is not a filehandle or a scalar
1103variable containing a filehandle name or reference, then it is interpreted
1104as a filename pattern to be globbed, and either a list of filenames or the
1105next filename in the list is returned, depending on context. One level of
1106$ interpretation is done first, but you can't say C<E<lt>$fooE<gt>>
1107because that's an indirect filehandle as explained in the previous
1108paragraph. (In older versions of Perl, programmers would insert curly
1109brackets to force interpretation as a filename glob: C<E<lt>${foo}E<gt>>.
1110These days, it's considered cleaner to call the internal function directly
1111as C<glob($foo)>, which is probably the right way to have done it in the
1112first place.) Example:
1113
1114 while (<*.c>) {
1115 chmod 0644, $_;
1116 }
1117
1118is equivalent to
1119
1120 open(FOO, "echo *.c | tr -s ' \t\r\f' '\\012\\012\\012\\012'|");
1121 while (<FOO>) {
1122 chop;
1123 chmod 0644, $_;
1124 }
1125
1126In fact, it's currently implemented that way. (Which means it will not
1127work on filenames with spaces in them unless you have csh(1) on your
1128machine.) Of course, the shortest way to do the above is:
1129
1130 chmod 0644, <*.c>;
1131
1132Because globbing invokes a shell, it's often faster to call readdir() yourself
1133and do your own grep() on the filenames. Furthermore, due to its current
1134implementation of using a shell, the glob() routine may get "Arg list too
1135long" errors (unless you've installed tcsh(1L) as F</bin/csh>).
1136
1137A glob evaluates its (embedded) argument only when it is starting a new
1138list. All values must be read before it will start over. In a list
1139context this isn't important, because you automatically get them all
1140anyway. In a scalar context, however, the operator returns the next value
1141each time it is called, or a FALSE value if you've just run out. Again,
1142FALSE is returned only once. So if you're expecting a single value from
1143a glob, it is much better to say
1144
1145 ($file) = <blurch*>;
1146
1147than
1148
1149 $file = <blurch*>;
1150
1151because the latter will alternate between returning a filename and
1152returning FALSE.
1153
1154It you're trying to do variable interpolation, it's definitely better
1155to use the glob() function, because the older notation can cause people
1156to become confused with the indirect filehandle notation.
1157
1158 @files = glob("$dir/*.[ch]");
1159 @files = glob($files[$i]);
1160
1161=head2 Constant Folding
1162
1163Like C, Perl does a certain amount of expression evaluation at
1164compile time, whenever it determines that all of the arguments to an
1165operator are static and have no side effects. In particular, string
1166concatenation happens at compile time between literals that don't do
1167variable substitution. Backslash interpretation also happens at
1168compile time. You can say
1169
1170 'Now is the time for all' . "\n" .
1171 'good men to come to.'
1172
1173and this all reduces to one string internally. Likewise, if
1174you say
1175
1176 foreach $file (@filenames) {
1177 if (-s $file > 5 + 100 * 2**16) { ... }
1178 }
1179
1180the compiler will precompute the number that
1181expression represents so that the interpreter
1182won't have to.
1183
1184
1185=head2 Integer Arithmetic
1186
1187By default Perl assumes that it must do most of its arithmetic in
1188floating point. But by saying
1189
1190 use integer;
1191
1192you may tell the compiler that it's okay to use integer operations
1193from here to the end of the enclosing BLOCK. An inner BLOCK may
1194countermand this by saying
1195
1196 no integer;
1197
1198which lasts until the end of that BLOCK.
1199
1200The bitwise operators ("&", "|", "^", "~", "<<", and ">>") always
1201produce integral results. However, C<use integer> still has meaning
1202for them. By default, their results are interpreted as unsigned
1203integers. However, if C<use integer> is in effect, their results are
1204interpreted as signed integers. For example, C<~0> usually evaluates
1205to a large integral value. However, C<use integer; ~0> is -1.
1206
1207=head2 Floating-point Arithmetic
1208
1209While C<use integer> provides integer-only arithmetic, there is no
1210similar ways to provide rounding or truncation at a certain number of
1211decimal places. For rounding to a certain number of digits, sprintf()
1212or printf() is usually the easiest route.
1213
1214The POSIX module (part of the standard perl distribution) implements
1215ceil(), floor(), and a number of other mathematical and trigonometric
1216functions. The Math::Complex module (part of the standard perl
1217distribution) defines a number of mathematical functions that can also
1218work on real numbers. Math::Complex not as efficient as POSIX, but
1219POSIX can't work with complex numbers.
1220
1221Rounding in financial applications can have serious implications, and
1222the rounding method used should be specified precisely. In these
1223cases, it probably pays not to trust whichever system rounding is
1224being used by Perl, but to instead implement the rounding function you
1225need yourself.