This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
perlre: fix typo
[perl5.git] / pod / perlre.pod
index b4bb45e..b4b7bf2 100644 (file)
@@ -72,27 +72,13 @@ are split between groupings, or when one or more are quantified.  Thus
  # be even if it did!!
  "\N{LATIN SMALL LIGATURE FI}" =~ /(f)(i)/i;      # Doesn't match!
 
-Perl doesn't match multiple characters in an inverted bracketed
-character class, which otherwise could be highly confusing.  See
+Perl doesn't match multiple characters in a bracketed
+character class unless the character that maps to them is explicitly
+mentioned, and it doesn't match them at all if the character class is
+inverted, which otherwise could be highly confusing.  See
+L<perlrecharclass/Bracketed Character Classes>, and
 L<perlrecharclass/Negation>.
 
-Another bug involves character classes that match both a sequence of
-multiple characters, and an initial sub-string of that sequence.  For
-example,
-
- /[s\xDF]/i
-
-should match both a single and a double "s", since C<\xDF> (on ASCII
-platforms) matches "ss".  However, this bug
-(L<[perl #89774]|https://rt.perl.org/rt3/Ticket/Display.html?id=89774>)
-causes it to only match a single "s", even if the final larger match
-fails, and matching the double "ss" would have succeeded.
-
-Also, Perl matching doesn't fully conform to the current Unicode C</i>
-recommendations, which ask that the matching be made upon the NFD
-(Normalization Form Decomposed) of the text.  However, Unicode is
-in the process of reconsidering and revising their recommendations.
-
 =item x
 X</x>
 
@@ -105,6 +91,9 @@ X</p> X<regex, preserve> X<regexp, preserve>
 Preserve the string matched such that ${^PREMATCH}, ${^MATCH}, and
 ${^POSTMATCH} are available for use after matching.
 
+In Perl 5.18 and higher this is ignored.  ${^PREMATCH}, ${^MATCH}, and
+${^POSTMATCH} will be available after the match regardless of the modifier.
+
 =item g and c
 X</g> X</c>
 
@@ -323,7 +312,11 @@ the pattern uses a Unicode name (C<\N{...}>);  or
 
 =item 5
 
-the pattern uses a Unicode property (C<\p{...}>)
+the pattern uses a Unicode property (C<\p{...}>); or
+
+=item 6
+
+the pattern uses L</C<(?[ ])>>
 
 =back
 
@@ -491,7 +484,7 @@ newline within the string (except if the newline is the last character in
 the string), and "$" will match before any newline.  At the
 cost of a little more overhead, you can do this by using the /m modifier
 on the pattern match operator.  (Older programs did this by setting C<$*>,
-but this option was removed in perl 5.9.)
+but this option was removed in perl 5.10.)
 X<^> X<$> X</m>
 
 To simplify multi-line substitutions, the "." character never matches a
@@ -885,9 +878,11 @@ B<NOTE>: Failed matches in Perl do not reset the match variables,
 which makes it easier to write code that tests for a series of more
 specific cases and remembers the best match.
 
-B<WARNING>: Once Perl sees that you need one of C<$&>, C<$`>, or
+B<WARNING>: If your code is to run on Perl 5.16 or earlier,
+beware that once Perl sees that you need one of C<$&>, C<$`>, or
 C<$'> anywhere in the program, it has to provide them for every
-pattern match.  This may substantially slow your program.  Perl
+pattern match.  This may substantially slow your program.  (In Perl 5.18 a
+more efficient mechanism is used, eliminating any slowdown.)  Perl
 uses the same mechanism to produce C<$1>, C<$2>, etc, so you also pay a
 price for each pattern that contains capturing parentheses.  (To
 avoid this cost while retaining the grouping behaviour, use the
@@ -896,17 +891,17 @@ use C<$&>, C<$`> or C<$'>, then patterns I<without> capturing
 parentheses will not be penalized.  So avoid C<$&>, C<$'>, and C<$`>
 if you can, but if you can't (and some algorithms really appreciate
 them), once you've used them once, use them at will, because you've
-already paid the price.  As of 5.005, C<$&> is not so costly as the
-other two.
+already paid the price. 
 X<$&> X<$`> X<$'>
 
-As a workaround for this problem, Perl 5.10.0 introduces C<${^PREMATCH}>,
+As a workaround for this problem, Perl 5.10.0 introduced C<${^PREMATCH}>,
 C<${^MATCH}> and C<${^POSTMATCH}>, which are equivalent to C<$`>, C<$&>
 and C<$'>, B<except> that they are only guaranteed to be defined after a
 successful match that was executed with the C</p> (preserve) modifier.
 The use of these variables incurs no global performance penalty, unlike
 their punctuation char equivalents, however at the trade-off that you
-have to tell perl when you want to use them.
+have to tell perl when you want to use them.  As of Perl 5.18, these three
+variables are equivalent to C<$`>, C<$&> and C<$'>, and C</p> is ignored.
 X</p> X<p modifier>
 
 =head2 Quoting metacharacters
@@ -1251,27 +1246,82 @@ X<(?{})> X<regex, code in> X<regexp, code in> X<regular expression, code in>
 B<WARNING>: This extended regular expression feature is considered
 experimental, and may be changed without notice. Code executed that
 has side effects may not perform identically from version to version
-due to the effect of future optimisations in the regex engine.
+due to the effect of future optimisations in the regex engine. The
+implementation of this feature was radically overhauled for the 5.18.0
+release, and its behaviour in earlier versions of perl was much buggier,
+especially in relation to parsing, lexical vars, scoping, recursion and
+reentrancy.
 
-This zero-width assertion evaluates any embedded Perl code.  It
-always succeeds, and its C<code> is not interpolated.  Currently,
-the rules to determine where the C<code> ends are somewhat convoluted.
+This zero-width assertion executes any embedded Perl code.  It always
+succeeds, and its return value is set as C<$^R>.
 
-This feature can be used together with the special variable C<$^N> to
-capture the results of submatches in variables without having to keep
-track of the number of nested parentheses. For example:
+In literal patterns, the code is parsed at the same time as the
+surrounding code. While within the pattern, control is passed temporarily
+back to the perl parser, until the logically-balancing closing brace is
+encountered. This is similar to the way that an array index expression in
+a literal string is handled, for example
 
-  $_ = "The brown fox jumps over the lazy dog";
-  /the (\S+)(?{ $color = $^N }) (\S+)(?{ $animal = $^N })/i;
-  print "color = $color, animal = $animal\n";
+    "abc$array[ 1 + f('[') + g()]def"
+
+In particular, braces do not need to be balanced:
+
+    s/abc(?{ f('{'); })/def/
+
+Even in a pattern that is interpolated and compiled at run-time, literal
+code blocks will be compiled once, at perl compile time; the following
+prints "ABCD":
+
+    print "D";
+    my $qr = qr/(?{ BEGIN { print "A" } })/;
+    my $foo = "foo";
+    /$foo$qr(?{ BEGIN { print "B" } })/;
+    BEGIN { print "C" }
+
+In patterns where the text of the code is derived from run-time
+information rather than appearing literally in a source code /pattern/,
+the code is compiled at the same time that the pattern is compiled, and
+for reasons of security, C<use re 'eval'> must be in scope. This is to
+stop user-supplied patterns containing code snippets from being
+executable.
+
+In situations where you need to enable this with C<use re 'eval'>, you should
+also have taint checking enabled.  Better yet, use the carefully
+constrained evaluation within a Safe compartment.  See L<perlsec> for
+details about both these mechanisms.
+
+From the viewpoint of parsing, lexical variable scope and closures,
+
+    /AAA(?{ BBB })CCC/
+
+behaves approximately like
+
+    /AAA/ && do { BBB } && /CCC/
 
-Inside the C<(?{...})> block, C<$_> refers to the string the regular
+Similarly,
+
+    qr/AAA(?{ BBB })CCC/
+
+behaves approximately like
+
+    sub { /AAA/ && do { BBB } && /CCC/ }
+
+In particular:
+
+    { my $i = 1; $r = qr/(?{ print $i })/ }
+    my $i = 2;
+    /$r/; # prints "1"
+
+Inside a C<(?{...})> block, C<$_> refers to the string the regular
 expression is matching against. You can also use C<pos()> to know what is
 the current position of matching within this string.
 
-The C<code> is properly scoped in the following sense: If the assertion
-is backtracked (compare L<"Backtracking">), all changes introduced after
-C<local>ization are undone, so that
+The code block introduces a new scope from the perspective of lexical
+variable declarations, but B<not> from the perspective of C<local> and
+similar localizing behaviours. So later code blocks within the same
+pattern will still see the values which were localized in earlier blocks.
+These accumulated localizations are undone either at the end of a
+successful match, or if the assertion is backtracked (compare
+L<"Backtracking">). For example,
 
   $_ = 'a' x 8;
   m<
@@ -1288,51 +1338,32 @@ C<local>ization are undone, so that
                                    # non-localized location.
    >x;
 
-will set C<$res = 4>.  Note that after the match, C<$cnt> returns to the globally
-introduced value, because the scopes that restrict C<local> operators
-are unwound.
+will initially increment C<$cnt> up to 8; then during backtracking, its
+value will be unwound back to 4, which is the value assigned to C<$res>.
+At the end of the regex execution, $cnt will be wound back to its initial
+value of 0.
+
+This assertion may be used as the condition in a
+
+    (?(condition)yes-pattern|no-pattern)
 
-This assertion may be used as a C<(?(condition)yes-pattern|no-pattern)>
-switch.  If I<not> used in this way, the result of evaluation of
-C<code> is put into the special variable C<$^R>.  This happens
-immediately, so C<$^R> can be used from other C<(?{ code })> assertions
-inside the same regular expression.
+switch.  If I<not> used in this way, the result of evaluation of C<code>
+is put into the special variable C<$^R>.  This happens immediately, so
+C<$^R> can be used from other C<(?{ code })> assertions inside the same
+regular expression.
 
 The assignment to C<$^R> above is properly localized, so the old
 value of C<$^R> is restored if the assertion is backtracked; compare
 L<"Backtracking">.
 
-For reasons of security, this construct is forbidden if the regular
-expression involves run-time interpolation of variables, unless the
-perilous C<use re 'eval'> pragma has been used (see L<re>), or the
-variables contain results of the C<qr//> operator (see
-L<perlop/"qr/STRINGE<sol>msixpodual">).
+Note that the special variable C<$^N>  is particularly useful with code
+blocks to capture the results of submatches in variables without having to
+keep track of the number of nested parentheses. For example:
 
-This restriction is due to the wide-spread and remarkably convenient
-custom of using run-time determined strings as patterns.  For example:
+  $_ = "The brown fox jumps over the lazy dog";
+  /the (\S+)(?{ $color = $^N }) (\S+)(?{ $animal = $^N })/i;
+  print "color = $color, animal = $animal\n";
 
-    $re = <>;
-    chomp $re;
-    $string =~ /$re/;
-
-Before Perl knew how to execute interpolated code within a pattern,
-this operation was completely safe from a security point of view,
-although it could raise an exception from an illegal pattern.  If
-you turn on the C<use re 'eval'>, though, it is no longer secure,
-so you should only do so if you are also using taint checking.
-Better yet, use the carefully constrained evaluation within a Safe
-compartment.  See L<perlsec> for details about both these mechanisms.
-
-B<WARNING>: Use of lexical (C<my>) variables in these blocks is
-broken. The result is unpredictable and will make perl unstable. The
-workaround is to use global (C<our>) variables.
-
-B<WARNING>: In perl 5.12.x and earlier, the regex engine
-was not re-entrant, so interpolated code could not
-safely invoke the regex engine either directly with
-C<m//> or C<s///>), or indirectly with functions such as
-C<split>. Invoking the regex engine in these blocks would make perl
-unstable.
 
 =item C<(??{ code })>
 X<(??{})>
@@ -1343,22 +1374,29 @@ experimental, and may be changed without notice. Code executed that
 has side effects may not perform identically from version to version
 due to the effect of future optimisations in the regex engine.
 
-This is a "postponed" regular subexpression.  The C<code> is evaluated
-at run time, at the moment this subexpression may match.  The result
-of evaluation is considered a regular expression and matched as
-if it were inserted instead of this construct.  Note that this means
-that the contents of capture groups defined inside an eval'ed pattern
-are not available outside of the pattern, and vice versa, there is no
-way for the inner pattern returned from the code block to refer to a
-capture group defined outside.  (The code block itself can use C<$1>, etc.,
-to refer to the enclosing pattern's capture groups.)  Thus,
+This is a "postponed" regular subexpression.  It behaves in I<exactly> the
+same way as a C<(?{ code })> code block as described above, except that
+its return value, rather than being assigned to C<$^R>, is treated as a
+pattern, compiled if it's a string (or used as-is if its a qr// object),
+then matched as if it were inserted instead of this construct.
 
-    ('a' x 100)=~/(??{'(.)' x 100})/
+During the matching of this sub-pattern, it has its own set of
+captures which are valid during the sub-match, but are discarded once
+control returns to the main pattern. For example, the following matches,
+with the inner pattern capturing "B" and matching "BB", while the outer
+pattern captures "A";
+
+    my $inner = '(.)\1';
+    "ABBA" =~ /^(.)(??{ $inner })\1/;
+    print $1; # prints "A";
 
-B<will> match, it will B<not> set $1.
+Note that this means that  there is no way for the inner pattern to refer
+to a capture group defined outside.  (The code block itself can use C<$1>,
+etc., to refer to the enclosing pattern's capture groups.)  Thus, although
 
-The C<code> is not interpolated.  As before, the rules to determine
-where the C<code> ends are currently somewhat convoluted.
+    ('a' x 100)=~/(??{'(.)' x 100})/
+
+I<will> match, it will I<not> set $1 on exit.
 
 The following pattern matches a parenthesized group:
 
@@ -1375,30 +1413,21 @@ The following pattern matches a parenthesized group:
 See also C<(?PARNO)> for a different, more efficient way to accomplish
 the same task.
 
-For reasons of security, this construct is forbidden if the regular
-expression involves run-time interpolation of variables, unless the
-perilous C<use re 'eval'> pragma has been used (see L<re>), or the
-variables contain results of the C<qr//> operator (see
-L<perlop/"qrE<sol>STRINGE<sol>msixpodual">).
-
-In perl 5.12.x and earlier, because the regex engine was not re-entrant,
-delayed code could not safely invoke the regex engine either directly with
-C<m//> or C<s///>), or indirectly with functions such as C<split>.
-
-Recursing deeper than 50 times without consuming any input string will
-result in a fatal error.  The maximum depth is compiled into perl, so
-changing it requires a custom build.
+Executing a postponed regular expression 50 times without consuming any
+input string will result in a fatal error.  The maximum depth is compiled
+into perl, so changing it requires a custom build.
 
 =item C<(?PARNO)> C<(?-PARNO)> C<(?+PARNO)> C<(?R)> C<(?0)>
 X<(?PARNO)> X<(?1)> X<(?R)> X<(?0)> X<(?-1)> X<(?+1)> X<(?-PARNO)> X<(?+PARNO)>
 X<regex, recursive> X<regexp, recursive> X<regular expression, recursive>
 X<regex, relative recursion>
 
-Similar to C<(??{ code })> except it does not involve compiling any code,
-instead it treats the contents of a capture group as an independent
-pattern that must match at the current position.  Capture groups
-contained by the pattern will have the value as determined by the
-outermost recursion.
+Similar to C<(??{ code })> except that it does not involve executing any
+code or potentially compiling a returned pattern string; instead it treats
+the part of the current pattern contained within a specified capture group
+as an independent pattern that must match at the current position.
+Capture groups contained by the pattern will have the value as determined
+by the outermost recursion.
 
 PARNO is a sequence of digits (not starting with 0) whose value reflects
 the paren-number of the capture group to recurse to. C<(?R)> recurses to
@@ -1487,11 +1516,11 @@ Conditional expression. Matches C<yes-pattern> if C<condition> yields
 a true value, matches C<no-pattern> otherwise. A missing pattern always
 matches.
 
-C<(condition)> should be either an integer in
+C<(condition)> should be one of: 1) an integer in
 parentheses (which is valid if the corresponding pair of parentheses
-matched), a look-ahead/look-behind/evaluate zero-width assertion, a
+matched); 2) a look-ahead/look-behind/evaluate zero-width assertion; 3) a
 name in angle brackets or single quotes (which is valid if a group
-with the given name matched), or the special symbol (R) (true when
+with the given name matched); or 4) the special symbol (R) (true when
 evaluated inside of recursion or eval). Additionally the R may be
 followed by a number, (which will be true when evaluated when recursing
 inside of the appropriate group), or by C<&NAME>, in which case it will
@@ -1704,6 +1733,141 @@ to inside of one of these constructs. The following equivalences apply:
     PAT?+               (?>PAT?)
     PAT{min,max}+       (?>PAT{min,max})
 
+=item C<(?[ ])>
+X<set operations>
+
+This is an experimental feature present starting in 5.18, but is subject
+to change as we gain field experience with it.  Any attempt to use it
+will raise a warning, unless disabled via
+
+ no warnings "experimental::regex_sets";
+
+Comments on this feature are welcome; send email to
+C<perl5-porters@perl.org>.
+
+This is a fancy bracketed character class that can be used for more
+readable and less error-prone classes, and to perform set operations,
+such as intersection. An example is
+
+ /(?[ \p{Thai} & \p{Digit} ])/
+
+This will match all the digit characters that are in the Thai script.
+We can extend this by
+
+ /(?[ ( \p{Thai} + \p{Lao} ) & \p{Digit} ])/
+
+This matches digits that are in either the Thai or Laotian scripts.
+
+Notice the white space in these examples.  This construct always has
+L</C<E<sol>x>> turned on.
+
+The available binary operators are:
+
+ &    intersection
+ +    union
+ |    another name for '+', hence means union
+ -    subtraction (the result matches the set consisting of those
+      code points matched by the first operand, excluding any that
+      are also matched by the second operand)
+ ^    symmetric difference (the union minus the intersection).  This
+      is like an exclusive or, in that the result is the set of code
+      points that are matched by either, but not both, of the
+      operands.
+
+There is one unary operator:
+
+ !    complement
+
+All the binary operators left associate, and are of equal precedence.
+The unary operator right associates, and has higher precedence.  Use
+parentheses to override the default associations.
+
+The main restriction is that everything is a metacharacter.  Thus,
+you cannot refer to single characters by doing something like this:
+
+ /(?[ a + b ])/ # Syntax error!
+
+The easiest way to specify an individual typable character is to enclose
+it in brackets:
+
+ /(?[ [a] + [b] ])/
+
+(This is the same thing as C<[ab]>.)  You could also have said the
+equivalent
+
+ /(?[[ a b ]])/
+
+(You can, of course, specify single characters by using, C<\x{ }>,
+C<\N{ }>, etc.)
+
+This last example shows the use of this construct to specify an ordinary
+bracketed character class without set operations.  Note the white space
+within it.  To specify a matchable white space character, you can escape
+it with a backslash, like:
+
+ /(?[ [ a e i o u \  ] ])/
+
+This matches the English vowels plus the SPACE character.
+All the other escapes accepted by normal bracketed character classes are
+accepted here as well; but unlike the normal ones, unrecognized escapes are
+fatal errors here.
+
+All warnings from these class elements are fatal, as well as some
+practices that don't currently warn.  For example you cannot say
+
+ /(?[ [ \xF ] ])/     # Syntax error!
+
+You have to have two hex digits after a braceless C<\x> (use a leading
+zero to make two).  These restrictions are to lower the incidence of
+typos causing the class to not match what you thought it would.
+
+The final difference between regular bracketed character classes and
+these, is that it is not possible to get the latter to match a
+multi-character fold.  Thus,
+
+ /(?[ [\xDF] ])/iu
+
+does not match the string C<ss>.
+
+You don't have to enclose Posix class names inside double brackets.  The
+following works
+
+ /(?[ [:word:] - [:lower:] ])/
+
+C<< (?[ ]) >> is a compile-time construct.  Any attempt to use something
+which isn't knowable until run-time is a fatal error.  Thus, this
+construct cannot be used within the scope of C<use locale> (or the
+L</C<E<sol>l>> regex modifier).  Any L<user-defined
+property|perlunicode/"User-Defined Character Properties"> used must be
+already defined by the time the regular expression is compiled; but note
+that this construct can be used to avoid defining such properties.
+
+A regular expression using this construct that otherwise would compile
+using L</C<E<sol>d>> rules will instead use L</C<E<sol>u>>.
+
+The L</C<E<sol>x>> processing within this class is an extended form.
+Besides the characters that are considered white space in normal C</x>
+processing, there are 5 others, recommended by the Unicode standard:
+
+ U+0085 NEXT LINE
+ U+200E LEFT-TO-RIGHT MARK
+ U+200F RIGHT-TO-LEFT MARK
+ U+2028 LINE SEPARATOR
+ U+2029 PARAGRAPH SEPARATOR
+
+Note that skipping white space applies only to the interior of this
+construct.  There must not be any space between any of the characters
+that form the initial C<(?[>.  Nor may there be space between the
+closing C<])> characters.
+
+Due to the way that Perl parses things, your parentheses and brackets
+may need to be balanced, even including comments.
+
+Since this experimental, we may change this so that other legal uses of
+normal bracketed character classes might become illegal.  One proposal,
+for example, is to forbid adjacent uses of the same character, as in
+C<[aa]>.  This is likely a typo, as the second "a" adds nothing.
+
 =back
 
 =head2 Special Backtracking Control Verbs
@@ -1889,11 +2053,11 @@ is the same as
 
 but
 
-  / ( A (*THEN) B | C (*THEN) D ) /
+  / ( A (*THEN) B | C ) /
 
 is not the same as
 
-  / ( A (*PRUNE) B | C (*PRUNE) D ) /
+  / ( A (*PRUNE) B | C ) /
 
 as after matching the A but failing on the B the C<(*THEN)> verb will
 backtrack and try C; but the C<(*PRUNE)> verb will simply fail.