X-Git-Url: https://perl5.git.perl.org/perl5.git/blobdiff_plain/023a2b404cea6fcd66ed3d6fd7f27663e85c4093..54e0f05ce4bb904f953dde352028f27b07cb1fdf:/pod/perlop.pod
diff --git a/pod/perlop.pod b/pod/perlop.pod
index 1993853..e11fff2 100644
--- a/pod/perlop.pod
+++ b/pod/perlop.pod
@@ -53,7 +53,7 @@ values only, not array values.
nonassoc list operators (rightward)
right not
left and
- left or xor err
+ left or xor
In the following sections, these operators are covered in precedence order.
@@ -194,13 +194,14 @@ Unary "!" performs logical negation, i.e., "not". See also C for a lower
precedence version of this.
X
-Unary "-" performs arithmetic negation if the operand is numeric. If
-the operand is an identifier, a string consisting of a minus sign
-concatenated with the identifier is returned. Otherwise, if the string
-starts with a plus or minus, a string starting with the opposite sign
-is returned. One effect of these rules is that -bareword is equivalent
+Unary "-" performs arithmetic negation if the operand is numeric,
+including any string that looks like a number. If the operand is
+an identifier, a string consisting of a minus sign concatenated
+with the identifier is returned. Otherwise, if the string starts
+with a plus or minus, a string starting with the opposite sign is
+returned. One effect of these rules is that -bareword is equivalent
to the string "-bareword". If, however, the string begins with a
-non-alphabetic character (exluding "+" or "-"), Perl will attempt to convert
+non-alphabetic character (excluding "+" or "-"), Perl will attempt to convert
the string to a numeric and the arithmetic negation is performed. If the
string cannot be cleanly converted to a numeric, Perl will give the warning
B.
@@ -235,9 +236,12 @@ of operation work on some other string. The right argument is a search
pattern, substitution, or transliteration. The left argument is what is
supposed to be searched, substituted, or transliterated instead of the default
$_. When used in scalar context, the return value generally indicates the
-success of the operation. Behavior in list context depends on the particular
-operator. See L"Regexp Quote-Like Operators"> for details and
-L for examples using these operators.
+success of the operation. The exceptions are substitution (s///)
+and transliteration (y///) with the C (non-destructive) option,
+which cause the Beturn value to be the result of the substitution.
+Behavior in list context depends on the particular operator.
+See L"Regexp Quote-Like Operators"> for details and L for
+examples using these operators.
If the right argument is an expression rather than a search pattern,
substitution, or transliteration, it is interpreted as a search pattern at run
@@ -251,6 +255,9 @@ pattern C<\>, which it will consider a syntax error.
Binary "!~" is just like "=~" except the return value is negated in
the logical sense.
+Binary "!~" with a non-destructive substitution (s///r) or transliteration
+(y///r) is a syntax error.
+
=head2 Multiplicative Operators
X
@@ -260,19 +267,29 @@ X<*>
Binary "/" divides two numbers.
X> X
-Binary "%" computes the modulus of two numbers. Given integer
+Binary "%" is the modulo operator, which computes the division
+remainder of its first argument with respect to its second argument.
+Given integer
operands C<$a> and C<$b>: If C<$b> is positive, then C<$a % $b> is
-C<$a> minus the largest multiple of C<$b> that is not greater than
+C<$a> minus the largest multiple of C<$b> less than or equal to
C<$a>. If C<$b> is negative, then C<$a % $b> is C<$a> minus the
smallest multiple of C<$b> that is not less than C<$a> (i.e. the
result will be less than or equal to zero). If the operands
-C<$a> and C<$b> are floting point values, only the integer portion
-of C<$a> and C<$b> will be used in the operation.
+C<$a> and C<$b> are floating point values and the absolute value of
+C<$b> (that is C) is less than C<(UV_MAX + 1)>, only
+the integer portion of C<$a> and C<$b> will be used in the operation
+(Note: here C means the maximum of the unsigned integer type).
+If the absolute value of the right operand (C) is greater than
+or equal to C<(UV_MAX + 1)>, "%" computes the floating-point remainder
+C<$r> in the equation C<($r = $a - $i*$b)> where C<$i> is a certain
+integer that makes C<$r> have the same sign as the right operand
+C<$b> (B as the left operand C<$a> like C function C)
+and the absolute value less than that of C<$b>.
Note that when C
-This is just like the C search, except that it matches only
-once between calls to the reset() operator. This is a useful
-optimization when you want to see only the first occurrence of
-something in each file of a set of files, for instance. Only C?>
-patterns local to the current package are reset.
+This operator quotes (and possibly compiles) its I as a regular
+expression. I is interpolated the same way as I
+in C. If "'" is used as the delimiter, no interpolation
+is done. Returns a Perl value which may be used instead of the
+corresponding C expression. The returned value is a
+normalized version of the original pattern. It magically differs from
+a string containing the same characters: C[ returns "Regexp",
+even though dereferencing the result returns undef.
- while (<>) {
- if (?^$?) {
- # blank line between header and body
- }
- } continue {
- reset if eof; # clear ?? status for next file
+For example,
+
+ $rex = qr/my.STRING/is;
+ print $rex; # prints (?si-xm:my.STRING)
+ s/$rex/foo/;
+
+is equivalent to
+
+ s/my.STRING/foo/is;
+
+The result may be used as a subpattern in a match:
+
+ $re = qr/$pattern/;
+ $string =~ /foo${re}bar/; # can be interpolated in other patterns
+ $string =~ $re; # or used standalone
+ $string =~ /$re/; # or this way
+
+Since Perl may compile the pattern at the moment of execution of qr()
+operator, using qr() may have speed advantages in some situations,
+notably if the result of qr() is used standalone:
+
+ sub match {
+ my $patterns = shift;
+ my @compiled = map qr/$_/i, @$patterns;
+ grep {
+ my $success = 0;
+ foreach my $pat (@compiled) {
+ $success = 1, last if /$pat/;
+ }
+ $success;
+ } @_;
}
-This usage is vaguely deprecated, which means it just might possibly
-be removed in some distant future version of Perl, perhaps somewhere
-around the year 2168.
+Precompilation of the pattern into an internal representation at
+the moment of qr() avoids a need to recompile the pattern every
+time a match C$pat/> is attempted. (Perl has many other internal
+optimizations, but none would be triggered in the above example if
+we did not use qr() operator.)
+
+Options (specified by the following modifiers) are:
+
+ m Treat string as multiple lines.
+ s Treat string as single line. (Make . match a newline)
+ i Do case-insensitive pattern matching.
+ x Use extended regular expressions.
+ p When matching preserve a copy of the matched string so
+ that ${^PREMATCH}, ${^MATCH}, ${^POSTMATCH} will be defined.
+ o Compile pattern only once.
-=item m/PATTERN/cgimosx
+If a precompiled pattern is embedded in a larger pattern then the effect
+of 'msixp' will be propagated appropriately. The effect of the 'o'
+modifier has is not propagated, being restricted to those patterns
+explicitly using it.
+
+Several other modifiers to control the character set semantics were
+added for 5.14 that, unlike the ones listed above, may not be used
+after the final pattern delimiter, but only following a C<"(?"> inside
+the regular expression. (It is planned in 5.16 to make them usable in
+the suffix position.) These are B>, B>, B>, and
+B>. They are documented in L.
+
+See L for additional information on valid syntax for STRING, and
+for a detailed look at the semantics of regular expressions.
+
+=item m/PATTERN/msixpogc
X X
X X X X
-X X X X X X
+X X X X X X X X
-=item /PATTERN/cgimosx
+=item /PATTERN/msixpogc
Searches a string for a pattern match, and in scalar context returns
true if it succeeds, false if it fails. If no string is specified
@@ -1070,22 +1359,21 @@ rather tightly.) See also L. See L for
discussion of additional considerations that apply when C
is in effect.
-Options are:
+Options are as described in C; in addition, the following match
+process modifiers are available:
- c Do not reset search position on a failed match when /g is in effect.
- g Match globally, i.e., find all occurrences.
- i Do case-insensitive pattern matching.
- m Treat string as multiple lines.
- o Compile pattern only once.
- s Treat string as single line.
- x Use extended regular expressions.
+ g Match globally, i.e., find all occurrences.
+ c Do not reset search position on a failed match when /g is in effect.
If "/" is the delimiter then the initial C is optional. With the C
-you can use any pair of non-alphanumeric, non-whitespace characters
+you can use any pair of non-whitespace characters
as delimiters. This is particularly useful for matching path names
that contain "/", to avoid LTS (leaning toothpick syndrome). If "?" is
-the delimiter, then the match-only-once rule of C applies.
+the delimiter, then a match-only-once rule applies,
+described in C below.
If "'" is the delimiter, no interpolation is performed on the PATTERN.
+When using a character valid in an identifier, whitespace is required
+after the C.
PATTERN may contain variables, which will be interpolated (and the
pattern recompiled) every time the pattern search is evaluated, except
@@ -1096,7 +1384,9 @@ the trailing delimiter. This avoids expensive run-time recompilations,
and is useful when the value you are interpolating won't change over
the life of the script. However, mentioning C constitutes a promise
that you won't change the variables in the pattern. If you change them,
-Perl won't even notice. See also L<"qr/STRING/imosx">.
+Perl won't even notice. See also L<"qr/STRING/msixpo">.
+
+=item The empty pattern //
If the PATTERN evaluates to the empty string, the last
I matched regular expression is used instead. In this
@@ -1114,6 +1404,8 @@ will assume you meant defined-or. If you meant the empty regex, just
use parentheses or spaces to disambiguate, or even prefix the empty
regex with an C (so C/> becomes C).
+=item Matching in list context
+
If the C option is not used, C in list context returns a
list consisting of the subexpressions matched by the parentheses in the
pattern, i.e., (C<$1>, C<$2>, C<$3>...). (Note that here C<$1> etc. are
@@ -1145,29 +1437,33 @@ $Etc. The conditional is true if any variables were assigned, i.e., if
the pattern matched.
The C modifier specifies global pattern matching--that is,
-matching as many times as possible within the string. How it behaves
-depends on the context. In list context, it returns a list of the
+matching as many times as possible within the string. How it behaves
+depends on the context. In list context, it returns a list of the
substrings matched by any capturing parentheses in the regular
-expression. If there are no parentheses, it returns a list of all
+expression. If there are no parentheses, it returns a list of all
the matched strings, as if there were parentheses around the whole
pattern.
In scalar context, each execution of C finds the next match,
returning true if it matches, and false if there is no further match.
-The position after the last match can be read or set using the pos()
-function; see L. A failed match normally resets the
+The position after the last match can be read or set using the C
+function; see L. A failed match normally resets the
search position to the beginning of the string, but you can avoid that
-by adding the C modifier (e.g. C). Modifying the target
+by adding the C modifier (e.g. C). Modifying the target
string also resets the search position.
+=item \G assertion
+
You can intermix C matches with C, where C<\G> is a
-zero-width assertion that matches the exact position where the previous
-C, if any, left off. Without the C modifier, the C<\G> assertion
-still anchors at pos(), but the match is of course only attempted once.
-Using C<\G> without C on a target string that has not previously had a
-C match applied to it is the same as using the C<\A> assertion to match
-the beginning of the string. Note also that, currently, C<\G> is only
-properly supported when anchored at the very beginning of the pattern.
+zero-width assertion that matches the exact position where the
+previous C, if any, left off. Without the C modifier, the
+C<\G> assertion still anchors at C as it was at the start of
+the operation (see L), but the match is of course only
+attempted once. Using C<\G> without C on a target string that has
+not previously had a C match applied to it is the same as using
+the C<\A> assertion to match the beginning of the string. Note also
+that, currently, C<\G> is only properly supported when anchored at the
+very beginning of the pattern.
Examples:
@@ -1207,7 +1503,7 @@ The last example should print:
Notice that the final match matched C] instead of C, which a match
without the C<\G> anchor would have done. Also note that the final match
-did not update C -- C is only updated on a C match. If the
+did not update C. C is only updated on a C match. If the
final match did indeed match C, it's a good bet that you're running an
older (pre-5.6.0) Perl.
@@ -1217,26 +1513,181 @@ doing different actions depending on which regexp matched. Each
regexp tries to match where the previous one leaves off.
$_ = <<'EOL';
- $url = URI::URL->new( "http://www/" ); die if $url eq "xXx";
+ $url = URI::URL->new( "http://example.com/" ); die if $url eq "xXx";
EOL
LOOP:
{
- print(" digits"), redo LOOP if /\G\d+\b[,.;]?\s*/gc;
- print(" lowercase"), redo LOOP if /\G[a-z]+\b[,.;]?\s*/gc;
- print(" UPPERCASE"), redo LOOP if /\G[A-Z]+\b[,.;]?\s*/gc;
- print(" Capitalized"), redo LOOP if /\G[A-Z][a-z]+\b[,.;]?\s*/gc;
- print(" MiXeD"), redo LOOP if /\G[A-Za-z]+\b[,.;]?\s*/gc;
- print(" alphanumeric"), redo LOOP if /\G[A-Za-z0-9]+\b[,.;]?\s*/gc;
- print(" line-noise"), redo LOOP if /\G[^A-Za-z0-9]+/gc;
- print ". That's all!\n";
+ print(" digits"), redo LOOP if /\G\d+\b[,.;]?\s*/gc;
+ print(" lowercase"), redo LOOP if /\G[a-z]+\b[,.;]?\s*/gc;
+ print(" UPPERCASE"), redo LOOP if /\G[A-Z]+\b[,.;]?\s*/gc;
+ print(" Capitalized"), redo LOOP if /\G[A-Z][a-z]+\b[,.;]?\s*/gc;
+ print(" MiXeD"), redo LOOP if /\G[A-Za-z]+\b[,.;]?\s*/gc;
+ print(" alphanumeric"), redo LOOP if /\G[A-Za-z0-9]+\b[,.;]?\s*/gc;
+ print(" line-noise"), redo LOOP if /\G[^A-Za-z0-9]+/gc;
+ print ". That's all!\n";
}
Here is the output (split into several lines):
- line-noise lowercase line-noise lowercase UPPERCASE line-noise
- UPPERCASE line-noise lowercase line-noise lowercase line-noise
- lowercase lowercase line-noise lowercase lowercase line-noise
- MiXeD line-noise. That's all!
+ line-noise lowercase line-noise UPPERCASE line-noise UPPERCASE
+ line-noise lowercase line-noise lowercase line-noise lowercase
+ lowercase line-noise lowercase lowercase line-noise lowercase
+ lowercase line-noise MiXeD line-noise. That's all!
+
+=item m?PATTERN?
+X> X
+
+=item ?PATTERN?
+
+This is just like the C search, except that it matches
+only once between calls to the reset() operator. This is a useful
+optimization when you want to see only the first occurrence of
+something in each file of a set of files, for instance. Only C
+patterns local to the current package are reset.
+
+ while (<>) {
+ if (m?^$?) {
+ # blank line between header and body
+ }
+ } continue {
+ reset if eof; # clear m?? status for next file
+ }
+
+The match-once behaviour is controlled by the match delimiter being
+C>; with any other delimiter this is the normal C operator.
+
+For historical reasons, the leading C in C is optional,
+but the resulting C syntax is deprecated, will warn on
+usage and may be removed from a future stable release of Perl without
+further notice.
+
+=item s/PATTERN/REPLACEMENT/msixpogcer
+X X X X
+X X X X X X
X X X X X
+
+Searches a string for a pattern, and if found, replaces that pattern
+with the replacement text and returns the number of substitutions
+made. Otherwise it returns false (specifically, the empty string).
+
+If the C (non-destructive) option is used then it will perform the
+substitution on a copy of the string and return the copy whether or not a
+substitution occurred. The original string will always remain unchanged in
+this case. The copy will always be a plain string, even if the input is an
+object or a tied variable.
+
+If no string is specified via the C<=~> or C operator, the C<$_>
+variable is searched and modified. (The string specified with C<=~> must
+be scalar variable, an array element, a hash element, or an assignment
+to one of those, i.e., an lvalue.)
+
+If the delimiter chosen is a single quote, no interpolation is
+done on either the PATTERN or the REPLACEMENT. Otherwise, if the
+PATTERN contains a $ that looks like a variable rather than an
+end-of-string test, the variable will be interpolated into the pattern
+at run-time. If you want the pattern compiled only once the first time
+the variable is interpolated, use the C option. If the pattern
+evaluates to the empty string, the last successfully executed regular
+expression is used instead. See L for further explanation on these.
+See L for discussion of additional considerations that apply
+when C is in effect.
+
+Options are as with m// with the addition of the following replacement
+specific options:
+
+ e Evaluate the right side as an expression.
+ ee Evaluate the right side as a string then eval the result.
+ r Return substitution and leave the original string untouched.
+
+Any non-whitespace delimiter may replace the slashes. Add space after
+the C when using a character allowed in identifiers. If single quotes
+are used, no interpretation is done on the replacement string (the C
+modifier overrides this, however). Unlike Perl 4, Perl 5 treats backticks
+as normal delimiters; the replacement text is not evaluated as a command.
+If the PATTERN is delimited by bracketing quotes, the REPLACEMENT has
+its own pair of quotes, which may or may not be bracketing quotes, e.g.,
+C or C<< s/bar/ >>. A C will cause the
+replacement portion to be treated as a full-fledged Perl expression
+and evaluated right then and there. It is, however, syntax checked at
+compile-time. A second C modifier will cause the replacement portion
+to be Ced before being run as a Perl expression.
+
+Examples:
+
+ s/\bgreen\b/mauve/g; # don't change wintergreen
+
+ $path =~ s|/usr/bin|/usr/local/bin|;
+
+ s/Login: $foo/Login: $bar/; # run-time pattern
+
+ ($foo = $bar) =~ s/this/that/; # copy first, then change
+ ($foo = "$bar") =~ s/this/that/; # convert to string, copy, then change
+ $foo = $bar =~ s/this/that/r; # Same as above using /r
+ $foo = $bar =~ s/this/that/r
+ =~ s/that/the other/r; # Chained substitutes using /r
+ @foo = map { s/this/that/r } @bar # /r is very useful in maps
+
+ $count = ($paragraph =~ s/Mister\b/Mr./g); # get change-count
+
+ $_ = 'abc123xyz';
+ s/\d+/$&*2/e; # yields 'abc246xyz'
+ s/\d+/sprintf("%5d",$&)/e; # yields 'abc 246xyz'
+ s/\w/$& x 2/eg; # yields 'aabbcc 224466xxyyzz'
+
+ s/%(.)/$percent{$1}/g; # change percent escapes; no /e
+ s/%(.)/$percent{$1} || $&/ge; # expr now, so /e
+ s/^=(\w+)/pod($1)/ge; # use function call
+
+ $_ = 'abc123xyz';
+ $a = s/abc/def/r; # $a is 'def123xyz' and
+ # $_ remains 'abc123xyz'.
+
+ # expand variables in $_, but dynamics only, using
+ # symbolic dereferencing
+ s/\$(\w+)/${$1}/g;
+
+ # Add one to the value of any numbers in the string
+ s/(\d+)/1 + $1/eg;
+
+ # This will expand any embedded scalar variable
+ # (including lexicals) in $_ : First $1 is interpolated
+ # to the variable name, and then evaluated
+ s/(\$\w+)/$1/eeg;
+
+ # Delete (most) C comments.
+ $program =~ s {
+ /\* # Match the opening delimiter.
+ .*? # Match a minimal number of characters.
+ \*/ # Match the closing delimiter.
+ } []gsx;
+
+ s/^\s*(.*?)\s*$/$1/; # trim whitespace in $_, expensively
+
+ for ($variable) { # trim whitespace in $variable, cheap
+ s/^\s+//;
+ s/\s+$//;
+ }
+
+ s/([^ ]*) *([^ ]*)/$2 $1/; # reverse 1st two fields
+
+Note the use of $ instead of \ in the last example. Unlike
+B, we use the \> form in only the left hand side.
+Anywhere else it's $>.
+
+Occasionally, you can't use just a C to get all the changes
+to occur that you might want. Here are two common cases:
+
+ # put commas in the right places in an integer
+ 1 while s/(\d)(\d\d\d)(?!\d)/$1,$2/g;
+
+ # expand tabs to 8-column spacing
+ 1 while s/\t+/' ' x (length($&)*8 - length($`)%8)/e;
+
+=back
+
+=head2 Quote-Like Operators
+X
+
+=over 4
=item q/STRING/
X X X<'> X<''>
@@ -1263,64 +1714,6 @@ A double-quoted, interpolated string.
if /\b(tcl|java|python)\b/i; # :-)
$baz = "\n"; # a one-character string
-=item qr/STRING/imosx
-X X
X
X X X
-
-This operator quotes (and possibly compiles) its I as a regular
-expression. I is interpolated the same way as I
-in C. If "'" is used as the delimiter, no interpolation
-is done. Returns a Perl value which may be used instead of the
-corresponding C expression.
-
-For example,
-
- $rex = qr/my.STRING/is;
- s/$rex/foo/;
-
-is equivalent to
-
- s/my.STRING/foo/is;
-
-The result may be used as a subpattern in a match:
-
- $re = qr/$pattern/;
- $string =~ /foo${re}bar/; # can be interpolated in other patterns
- $string =~ $re; # or used standalone
- $string =~ /$re/; # or this way
-
-Since Perl may compile the pattern at the moment of execution of qr()
-operator, using qr() may have speed advantages in some situations,
-notably if the result of qr() is used standalone:
-
- sub match {
- my $patterns = shift;
- my @compiled = map qr/$_/i, @$patterns;
- grep {
- my $success = 0;
- foreach my $pat (@compiled) {
- $success = 1, last if /$pat/;
- }
- $success;
- } @_;
- }
-
-Precompilation of the pattern into an internal representation at
-the moment of qr() avoids a need to recompile the pattern every
-time a match C$pat/> is attempted. (Perl has many other internal
-optimizations, but none would be triggered in the above example if
-we did not use qr() operator.)
-
-Options are:
-
- i Do case-insensitive pattern matching.
- m Treat string as multiple lines.
- o Compile pattern only once.
- s Treat string as single line.
- x Use extended regular expressions.
-
-See L for additional information on valid syntax for STRING, and
-for a detailed look at the semantics of regular expressions.
-
=item qx/STRING/
X X<`> X<``> X
@@ -1441,119 +1834,11 @@ put comments into a multi-line C-string. For this reason, the
C pragma and the B<-w> switch (that is, the C<$^W> variable)
produces warnings if the STRING contains the "," or the "#" character.
-=item s/PATTERN/REPLACEMENT/egimosx
-X X X X
-X X X X X X X X
-
-Searches a string for a pattern, and if found, replaces that pattern
-with the replacement text and returns the number of substitutions
-made. Otherwise it returns false (specifically, the empty string).
-If no string is specified via the C<=~> or C operator, the C<$_>
-variable is searched and modified. (The string specified with C<=~> must
-be scalar variable, an array element, a hash element, or an assignment
-to one of those, i.e., an lvalue.)
-
-If the delimiter chosen is a single quote, no interpolation is
-done on either the PATTERN or the REPLACEMENT. Otherwise, if the
-PATTERN contains a $ that looks like a variable rather than an
-end-of-string test, the variable will be interpolated into the pattern
-at run-time. If you want the pattern compiled only once the first time
-the variable is interpolated, use the C option. If the pattern
-evaluates to the empty string, the last successfully executed regular
-expression is used instead. See L for further explanation on these.
-See L for discussion of additional considerations that apply
-when C is in effect.
-
-Options are:
-
- e Evaluate the right side as an expression.
- g Replace globally, i.e., all occurrences.
- i Do case-insensitive pattern matching.
- m Treat string as multiple lines.
- o Compile pattern only once.
- s Treat string as single line.
- x Use extended regular expressions.
-
-Any non-alphanumeric, non-whitespace delimiter may replace the
-slashes. If single quotes are used, no interpretation is done on the
-replacement string (the C modifier overrides this, however). Unlike
-Perl 4, Perl 5 treats backticks as normal delimiters; the replacement
-text is not evaluated as a command. If the
-PATTERN is delimited by bracketing quotes, the REPLACEMENT has its own
-pair of quotes, which may or may not be bracketing quotes, e.g.,
-C or C<< s/bar/ >>. A C will cause the
-replacement portion to be treated as a full-fledged Perl expression
-and evaluated right then and there. It is, however, syntax checked at
-compile-time. A second C modifier will cause the replacement portion
-to be Ced before being run as a Perl expression.
-
-Examples:
-
- s/\bgreen\b/mauve/g; # don't change wintergreen
-
- $path =~ s|/usr/bin|/usr/local/bin|;
-
- s/Login: $foo/Login: $bar/; # run-time pattern
-
- ($foo = $bar) =~ s/this/that/; # copy first, then change
-
- $count = ($paragraph =~ s/Mister\b/Mr./g); # get change-count
-
- $_ = 'abc123xyz';
- s/\d+/$&*2/e; # yields 'abc246xyz'
- s/\d+/sprintf("%5d",$&)/e; # yields 'abc 246xyz'
- s/\w/$& x 2/eg; # yields 'aabbcc 224466xxyyzz'
-
- s/%(.)/$percent{$1}/g; # change percent escapes; no /e
- s/%(.)/$percent{$1} || $&/ge; # expr now, so /e
- s/^=(\w+)/pod($1)/ge; # use function call
-
- # expand variables in $_, but dynamics only, using
- # symbolic dereferencing
- s/\$(\w+)/${$1}/g;
-
- # Add one to the value of any numbers in the string
- s/(\d+)/1 + $1/eg;
-
- # This will expand any embedded scalar variable
- # (including lexicals) in $_ : First $1 is interpolated
- # to the variable name, and then evaluated
- s/(\$\w+)/$1/eeg;
-
- # Delete (most) C comments.
- $program =~ s {
- /\* # Match the opening delimiter.
- .*? # Match a minimal number of characters.
- \*/ # Match the closing delimiter.
- } []gsx;
-
- s/^\s*(.*?)\s*$/$1/; # trim whitespace in $_, expensively
-
- for ($variable) { # trim whitespace in $variable, cheap
- s/^\s+//;
- s/\s+$//;
- }
-
- s/([^ ]*) *([^ ]*)/$2 $1/; # reverse 1st two fields
-
-Note the use of $ instead of \ in the last example. Unlike
-B, we use the \> form in only the left hand side.
-Anywhere else it's $>.
-
-Occasionally, you can't use just a C to get all the changes
-to occur that you might want. Here are two common cases:
-
- # put commas in the right places in an integer
- 1 while s/(\d)(\d\d\d)(?!\d)/$1,$2/g;
-
- # expand tabs to 8-column spacing
- 1 while s/\t+/' ' x (length($&)*8 - length($`)%8)/e;
-
-=item tr/SEARCHLIST/REPLACEMENTLIST/cds
+=item tr/SEARCHLIST/REPLACEMENTLIST/cdsr
X X X X X X
-=item y/SEARCHLIST/REPLACEMENTLIST/cds
+=item y/SEARCHLIST/REPLACEMENTLIST/cdsr
Transliterates all occurrences of the characters found in the search list
with the corresponding character in the replacement list. It returns
@@ -1562,6 +1847,12 @@ specified via the =~ or !~ operator, the $_ string is transliterated. (The
string specified with =~ must be a scalar variable, an array element, a
hash element, or an assignment to one of those, i.e., an lvalue.)
+If the C (non-destructive) option is used then it will perform the
+replacement on a copy of the string and return the copy whether or not it
+was modified. The original string will always remain unchanged in
+this case. The copy will always be a plain string, even if the input is an
+object or a tied variable.
+
A character range may be specified with a hyphen, so C
does the same replacement as C
.
For B devotees, C is provided as a synonym for C. If the
@@ -1570,7 +1861,7 @@ its own pair of quotes, which may or may not be bracketing quotes,
e.g., C
or C
.
Note that C does B do regular expression character classes
-such as C<\d> or C<[:lower:]>. The operator is not equivalent to
+such as C<\d> or C<[:lower:]>. The C
operator is not equivalent to
the tr(1) utility. If you want to map strings between lower/upper
cases, see L and L, and in general consider
using the C operator if you need regular expressions.
@@ -1587,6 +1878,8 @@ Options:
c Complement the SEARCHLIST.
d Delete found but unreplaced characters.
s Squash duplicate replaced characters.
+ r Return the modified string and leave the original string
+ untouched.
If the C modifier is specified, the SEARCHLIST character set
is complemented. If the C modifier is specified, any characters
@@ -1617,9 +1910,16 @@ Examples:
tr/a-zA-Z//s; # bookkeeper -> bokeper
($HOST = $host) =~ tr/a-z/A-Z/;
+ $HOST = $host =~ tr/a-z/A-Z/r; # same thing
+
+ $HOST = $host =~ tr/a-z/A-Z/r # chained with s///
+ =~ s/:/ -p/r;
tr/a-zA-Z/ /cs; # change non-alphas to single space
+ @stripped = map tr/a-zA-Z/ /csr, @original;
+ # /r with map
+
tr [\200-\377]
[\000-\177]; # delete 8th bit
@@ -1760,7 +2060,7 @@ must be sure there is a newline after it; otherwise, Perl will give the
warning B.
Additionally, the quoting rules for the end of string identifier are not
-related to Perl's quoting rules -- C, C, and the like are not
+related to Perl's quoting rules. C, C, and the like are not
supported in place of C<''> and C<"">, and the only interpolation is for
backslashing the quoting character:
@@ -1972,20 +2272,20 @@ is emitted if the C pragma or the B<-w> command-line flag
=item C in C, C, C, C,
-Processing of C<\Q>, C<\U>, C<\u>, C<\L>, C<\l>, and interpolation
-happens (almost) as with C constructs.
-
-However combinations of C<\> followed by RE-special chars are not
-substituted but only skipped. The full list of RE-special chars is
-C<\>, C<.>, C<^>, C<$>, C<@>, C, C, C, C, C, C, C,
-C, C, C, C, C, C
, C, C, C<+>, C<*>, C>, C<|>,
-C<(>, C<)>, C<->, C, C, C, C, C, C, C, C, C,
-digits (C<0> to C<9>), C<[>, C<{>, C<]>, C<}>, whitespaces (SPACE, TAB,
-LF, CR, FF, and VT in addition), and C<#>.
+Processing of C<\Q>, C<\U>, C<\u>, C<\L>, C<\l>, C<\E>,
+and interpolation happens (almost) as with C constructs.
+
+Processing of C<\N{...}> is also done here, and compiled into an intermediate
+form for the regex compiler. (This is because, as mentioned below, the regex
+compilation may be done at execution time, and C<\N{...}> is a compile-time
+construct.)
+
+However any other combinations of C<\> followed by a character
+are not substituted but only skipped, in order to parse them
+as regular expressions at the following step.
As C<\c> is skipped at this step, C<@> of C<\c@> in RE is possibly
treated as an array symbol (for example C<@foo>),
even though the same text in C gives interpolation of C<\c@>.
-Note that C<\N{name}> is interpolated at this step.
Moreover, inside C<(?{BLOCK})>, C<(?# comment )>, and
a C<#>-comment in a C/x>-regular expression, no processing is
@@ -2029,7 +2329,7 @@ which are processed further.
X
Previous steps were performed during the compilation of Perl code,
-but this one happens at run time--although it may be optimized to
+but this one happens at run time, although it may be optimized to
be calculated at compile time if appropriate. After preprocessing
described above, and possibly after evaluation if concatenation,
joining, casing translation, or metaquoting are involved, the
@@ -2142,8 +2442,8 @@ to terminate the loop, they should be tested for explicitly:
while (($_ = ) ne '0') { ... }
while () { last unless $_; ... }
-In other boolean contexts, C<< > >> without an
-explicit C test or comparison elicit a warning if the
+In other boolean contexts, C<< >> without an
+explicit C test or comparison elicits a warning if the
C pragma or the B<-w>
command-line switch (the C<$^W> variable) is in effect.
@@ -2188,10 +2488,22 @@ is equivalent to the following Perl-like pseudo code:
except that it isn't so cumbersome to say, and will actually work.
It really does shift the @ARGV array and put the current filename
into the $ARGV variable. It also uses filehandle I
-internally--<> is just a synonym for , which
+internally. <> is just a synonym for , which
is magical. (The pseudo code above doesn't work because it treats
as non-magical.)
+Since the null filehandle uses the two argument form of L
+it interprets special characters, so if you have a script like this:
+
+ while (<>) {
+ print;
+ }
+
+and call it with C, it actually opens a
+pipe, executes the C command and reads C's output from that pipe.
+If you want all items in C<@ARGV> to be interpreted as file names, you
+can use the module C from CPAN.
+
You can modify @ARGV before the first <> as long as the array ends up
containing the list of filenames you really want. Line numbers (C<$.>)
continue as though the input were one big happy file. See the example
@@ -2373,17 +2685,17 @@ floating point. But by saying
use integer;
-you may tell the compiler that it's okay to use integer operations
-(if it feels like it) from here to the end of the enclosing BLOCK.
-An inner BLOCK may countermand this by saying
+you may tell the compiler to use integer operations
+(see L for a detailed explanation) from here to the end of
+the enclosing BLOCK. An inner BLOCK may countermand this by saying
no integer;
which lasts until the end of that BLOCK. Note that this doesn't
-mean everything is only an integer, merely that Perl may use integer
-operations if it is so inclined. For example, even under C, if you take the C, you'll still get C<1.4142135623731>
-or so.
+mean everything is an integer, merely that Perl will use integer
+operations for arithmetic, comparison, and bitwise operators. For
+example, even under C, if you take the C, you'll
+still get C<1.4142135623731> or so.
Used on numbers, the bitwise operators ("&", "|", "^", "~", "<<",
and ">>") always produce integral results. (But see also
@@ -2410,8 +2722,8 @@ so some corners must be cut. For example:
printf "%.20g\n", 123456789123456789;
# produces 123456789123456784
-Testing for exact equality of floating-point equality or inequality is
-not a good idea. Here's a (relatively expensive) work-around to compare
+Testing for exact floating-point equality or inequality is not a
+good idea. Here's a (relatively expensive) work-around to compare
whether two floating-point numbers are equal to a particular number of
decimal places. See Knuth, volume II, for a more robust treatment of
this topic.
@@ -2459,17 +2771,17 @@ external C libraries.
Here is a short, but incomplete summary:
- Math::Fraction big, unlimited fractions like 9973 / 12967
- Math::String treat string sequences like numbers
- Math::FixedPrecision calculate with a fixed precision
- Math::Currency for currency calculations
- Bit::Vector manipulate bit vectors fast (uses C)
- Math::BigIntFast Bit::Vector wrapper for big numbers
- Math::Pari provides access to the Pari C library
- Math::BigInteger uses an external C library
- Math::Cephes uses external Cephes C library (no big numbers)
- Math::Cephes::Fraction fractions via the Cephes library
- Math::GMP another one using an external C library
+ Math::Fraction big, unlimited fractions like 9973 / 12967
+ Math::String treat string sequences like numbers
+ Math::FixedPrecision calculate with a fixed precision
+ Math::Currency for currency calculations
+ Bit::Vector manipulate bit vectors fast (uses C)
+ Math::BigIntFast Bit::Vector wrapper for big numbers
+ Math::Pari provides access to the Pari C library
+ Math::BigInteger uses an external C library
+ Math::Cephes uses external Cephes C library (no big numbers)
+ Math::Cephes::Fraction fractions via the Cephes library
+ Math::GMP another one using an external C library
Choose wisely.