This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
perldelta - Fix mistakes
[perl5.git] / pod / perlretut.pod
index aa89c3f..bf4ab3b 100644 (file)
@@ -176,7 +176,7 @@ In addition to the metacharacters, there are some ASCII characters
 which don't have printable character equivalents and are instead
 represented by I<escape sequences>.  Common examples are C<\t> for a
 tab, C<\n> for a newline, C<\r> for a carriage return and C<\a> for a
-bell.  If your string is better thought of as a sequence of arbitrary
+bell (or alert).  If your string is better thought of as a sequence of arbitrary
 bytes, the octal escape sequence, e.g., C<\033>, or hexadecimal escape
 sequence, e.g., C<\x1B> may be a more natural representation for your
 bytes.  Here are some examples of escapes:
@@ -367,8 +367,9 @@ character, or the match fails.  Then
 Now, even C<[0-9]> can be a bother to write multiple times, so in the
 interest of saving keystrokes and making regexps more readable, Perl
 has several abbreviations for common character classes, as shown below.
-Since the introduction of Unicode, these character classes match more
-than just a few characters in the ISO 8859-1 range.
+Since the introduction of Unicode, unless the C<//a> modifier is in
+effect, these character classes match more than just a few characters in
+the ASCII range.
 
 =over 4
 
@@ -402,8 +403,22 @@ but also digits and characters from non-roman scripts
 The period '.' matches any character but "\n" (unless the modifier C<//s> is
 in effect, as explained below).
 
+=item *
+
+\N, like the period, matches any character but "\n", but it does so
+regardless of whether the modifier C<//s> is in effect.
+
 =back
 
+The C<//a> modifier, available starting in Perl 5.14,  is used to
+restrict the matches of \d, \s, and \w to just those in the ASCII range.
+It is useful to keep your program from being needlessly exposed to full
+Unicode (and its accompanying security considerations) when all you want
+is to process English-like text.  (The "a" may be doubled, C<//aa>, to
+provide even more restrictions, preventing case-insensitive matching of
+ASCII with non-ASCII characters; otherwise a Unicode "Kelvin Sign"
+would caselessly match a "k" or "K".)
+
 The C<\d\s\w\D\S\W> abbreviations can be used both inside and outside
 of character classes.  Here are some in use:
 
@@ -766,7 +781,7 @@ so may lead to surprising and unsatisfactory results.
 =head2 Relative backreferences
 
 Counting the opening parentheses to get the correct number for a
-backreference is errorprone as soon as there is more than one
+backreference is error-prone as soon as there is more than one
 capturing group.  A more convenient technique became available
 with Perl 5.10: relative backreferences. To refer to the immediately
 preceding capture group one now may write C<\g{-1}>, the next but
@@ -854,7 +869,7 @@ with one higher than the maximum reached across all the alternatives.
 
 =head2 Position information
 
-In addition to what was matched, Perl (since 5.6.0) also provides the
+In addition to what was matched, Perl also provides the
 positions of what was matched as contents of the C<@-> and C<@+>
 arrays. C<$-[0]> is the position of the start of the entire match and
 C<$+[0]> is the position of the end. Similarly, C<$-[n]> is the
@@ -1501,31 +1516,6 @@ single line C<//s>, multi-line C<//m>, case-insensitive C<//i> and
 extended C<//x> modifiers.  There are a few more things you might
 want to know about matching operators.
 
-=head3 Optimizing pattern evaluation
-
-We pointed out earlier that variables in regexps are substituted
-before the regexp is evaluated:
-
-    $pattern = 'Seuss';
-    while (<>) {
-        print if /$pattern/;
-    }
-
-This will print any lines containing the word C<Seuss>.  It is not as
-efficient as it could be, however, because Perl has to re-evaluate
-(or compile) C<$pattern> each time through the loop.  If C<$pattern> won't be
-changing over the lifetime of the script, we can add the C<//o>
-modifier, which directs Perl to only perform variable substitutions
-once:
-
-    #!/usr/bin/perl
-    #    Improved simple_grep
-    $regexp = shift;
-    while (<>) {
-        print if /$regexp/o;  # a good deal faster
-    }
-
-
 =head3 Prohibiting substitution
 
 If you change C<$pattern> after the first substitution happens, Perl
@@ -1547,7 +1537,8 @@ the regexp in the I<last successful match> is used instead.  So we have
 
 =head3 Global matching
 
-The final two modifiers C<//g> and C<//c> concern multiple matches.
+The final two modifiers we will discuss here,
+C<//g> and C<//c>, concern multiple matches.
 The modifier C<//g> stands for global matching and allows the
 matching operator to match within a string as many times as possible.
 In scalar context, successive invocations against a string will have
@@ -1592,9 +1583,9 @@ there are no groupings, a list of matches to the whole regexp.  So if
 we wanted just the words, we could use
 
     @words = ($x =~ /(\w+)/g);  # matches,
-                                # $word[0] = 'cat'
-                                # $word[1] = 'dog'
-                                # $word[2] = 'house'
+                                # $words[0] = 'cat'
+                                # $words[1] = 'dog'
+                                # $words[2] = 'house'
 
 Closely associated with the C<//g> modifier is the C<\G> anchor.  The
 C<\G> anchor matches at the point where the previous C<//g> match left
@@ -1662,6 +1653,10 @@ which is the correct answer.  This example illustrates that it is
 important not only to match what is desired, but to reject what is not
 desired.
 
+(There are other regexp modifiers that are available, such as
+C<//o>, but their specialized uses are beyond the
+scope of this introduction.  )
+
 =head3 Search and replace
 
 Regular expressions also play a big role in I<search and replace>
@@ -1707,7 +1702,7 @@ the following program to replace it:
     $regexp = shift;
     $replacement = shift;
     while (<>) {
-        s/$regexp/$replacement/go;
+        s/$regexp/$replacement/g;
         print;
     }
     ^D
@@ -1715,13 +1710,15 @@ the following program to replace it:
     % simple_replace regexp regex perlretut.pod
 
 In C<simple_replace> we used the C<s///g> modifier to replace all
-occurrences of the regexp on each line and the C<s///o> modifier to
-compile the regexp only once.  As with C<simple_grep>, both the
-C<print> and the C<s/$regexp/$replacement/go> use C<$_> implicitly.
+occurrences of the regexp on each line.  (Even though the regular
+expression appears in a loop, Perl is smart enough to compile it
+only once.)  As with C<simple_grep>, both the
+C<print> and the C<s/$regexp/$replacement/g> use C<$_> implicitly.
 
 If you don't want C<s///> to change your original variable you can use
 the non-destructive substitute modifier, C<s///r>.  This changes the
-behavior so that C<s///r> returns the final substituted string:
+behavior so that C<s///r> returns the final substituted string
+(instead of the number of substitutions):
 
     $x = "I like dogs.";
     $y = $x =~ s/dogs/cats/r;
@@ -1871,12 +1868,14 @@ instance,
 It does not protect C<$> or C<@>, so that variables can still be
 substituted.
 
-C<\Q>, C<\L>, C<\U> and C<\E> are actually part of the syntax of regular
-expression I<literals>, and are not part of regexp syntax proper.  So they
-do not work in interpolated patterns.
+C<\Q>, C<\L>, C<\l>, C<\U>, C<\u> and C<\E> are actually part of
+double-quotish syntax, and not part of regexp syntax proper.  They will
+work if they appear in a regular expression embedded directly in a
+program, but not when contained in a string that is interpolated in a
+pattern.
 
-With the advent of 5.6.0, Perl regexps can handle more than just the
-standard ASCII character set.  Perl now supports I<Unicode>, a standard
+Perl regexps can handle more than just the
+standard ASCII character set.  Perl supports I<Unicode>, a standard
 for representing the alphabets from virtually all of the world's written
 languages, and a host of symbols.  Perl's text strings are Unicode strings, so
 they can contain characters with a value (codepoint or character number) higher
@@ -1888,8 +1887,8 @@ to know 1) how to represent Unicode characters in a regexp and 2) that
 a matching operation will treat the string to be searched as a sequence
 of characters, not bytes.  The answer to 1) is that Unicode characters
 greater than C<chr(255)> are represented using the C<\x{hex}> notation, because
-\x hex (without curly braces) doesn't go further than 255.  Starting in Perl
-5.14, if you're an octal fan, you can also use C<\o{oct}>.
+\x hex (without curly braces) doesn't go further than 255.  (Starting in Perl
+5.14, if you're an octal fan, you can also use C<\o{oct}>.)
 
     /\x{263a}/;  # match a Unicode smiley face :)
 
@@ -1908,30 +1907,36 @@ specified in the Unicode standard.  For instance, if we wanted to
 represent or match the astrological sign for the planet Mercury, we
 could use
 
-    use charnames ":full"; # use named chars with Unicode full names
     $x = "abc\N{MERCURY}def";
     $x =~ /\N{MERCURY}/;   # matches
 
-One can also use short names or restrict names to a certain alphabet:
+One can also use "short" names:
 
-    use charnames ':full';
     print "\N{GREEK SMALL LETTER SIGMA} is called sigma.\n";
-
-    use charnames ":short";
     print "\N{greek:Sigma} is an upper-case sigma.\n";
 
+You can also restrict names to a certain alphabet by specifying the
+L<charnames> pragma:
+
     use charnames qw(greek);
     print "\N{sigma} is Greek sigma\n";
 
-A list of full names is found in the file NamesList.txt in the
-lib/perl5/X.X.X/unicore directory (where X.X.X is the perl
-version number as it is installed on your system).
-
-The answer to requirement 2), as of 5.6.0, is that a regexp uses Unicode
-characters. Internally, this is encoded to bytes using either UTF-8 or a
-native 8 bit encoding, depending on the history of the string, but
-conceptually it is a sequence of characters, not bytes. See
-L<perlunitut> for a tutorial about that.
+An index of character names is available on-line from the Unicode
+Consortium, L<http://www.unicode.org/charts/charindex.html>; explanatory
+material with links to other resources at
+L<http://www.unicode.org/standard/where>.
+
+The answer to requirement 2) is that a regexp (mostly)
+uses Unicode characters.  The "mostly" is for messy backward
+compatibility reasons, but starting in Perl 5.14, any regex compiled in
+the scope of a C<use feature 'unicode_strings'> (which is automatically
+turned on within the scope of a C<use 5.012> or higher) will turn that
+"mostly" into "always".  If you want to handle Unicode properly, you
+should ensure that C<'unicode_strings'> is turned on.
+Internally, this is encoded to bytes using either UTF-8 or a native 8
+bit encoding, depending on the history of the string, but conceptually
+it is a sequence of characters, not bytes. See L<perlunitut> for a
+tutorial about that.
 
 Let us now discuss Unicode character classes.  Just as with Unicode
 characters, there are named Unicode character classes represented by the
@@ -1939,13 +1944,14 @@ C<\p{name}> escape sequence.  Closely associated is the C<\P{name}>
 character class, which is the negation of the C<\p{name}> class.  For
 example, to match lower and uppercase characters,
 
-    use charnames ":full"; # use named chars with Unicode full names
     $x = "BOB";
     $x =~ /^\p{IsUpper}/;   # matches, uppercase char class
     $x =~ /^\P{IsUpper}/;   # doesn't match, char class sans uppercase
     $x =~ /^\p{IsLower}/;   # doesn't match, lowercase char class
     $x =~ /^\P{IsLower}/;   # matches, char class sans lowercase
 
+(The "Is" is optional.)
+
 Here is the association between some Perl named classes and the
 traditional Unicode classes:
 
@@ -1978,10 +1984,7 @@ Unicode has also been separated into various sets of characters
 which you can test with C<\p{...}> (in) and C<\P{...}> (not in).
 To test whether a character is (or is not) an element of a script
 you would use the script name, for example C<\p{Latin}>, C<\p{Greek}>,
-or C<\P{Katakana}>. Other sets are the Unicode blocks, the names
-of which begin with "In". One such block is dedicated to mathematical
-operators, and its pattern formula is <C\p{InMathematicalOperators>}>.
-For the full list see L<perluniprops>.
+or C<\P{Katakana}>.
 
 What we have described so far is the single form of the C<\p{...}> character
 classes.  There is also a compound form which you may run into.  These
@@ -1995,7 +1998,7 @@ never have to use the compound forms, but sometimes it is necessary, and their
 use can make your code easier to understand.
 
 C<\X> is an abbreviation for a character class that comprises
-a Unicode I<extended grapheme cluster>.  This represents a "logical character",
+a Unicode I<extended grapheme cluster>.  This represents a "logical character":
 what appears to be a single character, but may be represented internally by more
 than one.  As an example, using the Unicode full names, e.g., S<C<A + COMBINING
 RING>> is a grapheme cluster with base character C<A> and combining character
@@ -2010,11 +2013,12 @@ character classes.  These have the form C<[:name:]>, with C<name> the
 name of the POSIX class.  The POSIX classes are C<alpha>, C<alnum>,
 C<ascii>, C<cntrl>, C<digit>, C<graph>, C<lower>, C<print>, C<punct>,
 C<space>, C<upper>, and C<xdigit>, and two extensions, C<word> (a Perl
-extension to match C<\w>), and C<blank> (a GNU extension).  If
-Unicode is enabled (see C<perlunicode/The "Unicode Bug">),
-then these classes are defined the same as their
-corresponding Perl Unicode classes: C<[:upper:]> is the same as
-C<\p{IsUpper}>, etc.  The C<[:digit:]>, C<[:word:]>, and
+extension to match C<\w>), and C<blank> (a GNU extension).  The C<//a>
+modifier restricts these to matching just in the ASCII range; otherwise
+they can match the same as their corresponding Perl Unicode classes:
+C<[:upper:]> is the same as C<\p{IsUpper}>, etc.  (There are some
+exceptions and gotchas with this; see L<perlrecharclass> for a full
+discussion.) The C<[:digit:]>, C<[:word:]>, and
 C<[:space:]> correspond to the familiar C<\d>, C<\w>, and C<\s>
 character classes.  To negate a POSIX class, put a C<^> in front of
 the name, so that, e.g., C<[:^digit:]> corresponds to C<\D> and, under
@@ -2033,8 +2037,8 @@ Whew! That is all the rest of the characters and character classes.
 
 =head2 Compiling and saving regular expressions
 
-In Part 1 we discussed the C<//o> modifier, which compiles a regexp
-just once.  This suggests that a compiled regexp is some data structure
+In Part 1 we mentioned that Perl compiles a regexp into a compact
+sequence of opcodes.  Thus, a compiled regexp is a data structure
 that can be stored once and used again and again.  The regexp quote
 C<qr//> does exactly that: C<qr/string/> compiles the C<string> as a
 regexp and transforms the result into a form that can be assigned to a
@@ -2109,7 +2113,7 @@ multiple patterns:
     $pattern = join '|', @regexp;
 
     while ($line = <>) {
-        print $line if $line =~ /$pattern/o;
+        print $line if $line =~ /$pattern/;
     }
     ^D
 
@@ -2177,7 +2181,7 @@ example is
 This style of commenting has been largely superseded by the raw,
 freeform commenting that is allowed with the C<//x> modifier.
 
-The modifiers C<//i>, C<//m>, C<//s> and C<//x> (or any
+Most modifiers, such as C<//i>, C<//m>, C<//s> and C<//x> (or any
 combination thereof) can also be embedded in
 a regexp using C<(?i)>, C<(?m)>, C<(?s)>, and C<(?x)>.  For instance,
 
@@ -2614,23 +2618,23 @@ C<(?((?{...}))yes-regexp|no-regexp)>.  In other words, in the case of a
 code expression, we don't need the extra parentheses around the
 conditional.
 
-If you try to use code expressions with interpolating variables, Perl
-may surprise you:
+If you try to use code expressions where the code text is contained within
+an interpolated variable, rather than appearing literally in the pattern,
+Perl may surprise you:
 
     $bar = 5;
     $pat = '(?{ 1 })';
     /foo(?{ $bar })bar/; # compiles ok, $bar not interpolated
-    /foo(?{ 1 })$bar/;   # compile error!
+    /foo(?{ 1 })$bar/;   # compiles ok, $bar interpolated
     /foo${pat}bar/;      # compile error!
 
     $pat = qr/(?{ $foo = 1 })/;  # precompile code regexp
     /foo${pat}bar/;      # compiles ok
 
-If a regexp has (1) code expressions and interpolating variables, or
-(2) a variable that interpolates a code expression, Perl treats the
-regexp as an error. If the code expression is precompiled into a
-variable, however, interpolating is ok. The question is, why is this
-an error?
+If a regexp has a variable that interpolates a code expression, Perl
+treats the regexp as an error. If the code expression is precompiled into
+a variable, however, interpolating is ok. The question is, why is this an
+error?
 
 The reason is that variable interpolation and code expressions
 together pose a security risk.  The combination is dangerous because
@@ -2653,7 +2657,6 @@ security check by invoking S<C<use re 'eval'>>:
     use re 'eval';       # throw caution out the door
     $bar = 5;
     $pat = '(?{ 1 })';
-    /foo(?{ 1 })$bar/;   # compiles ok
     /foo${pat}bar/;      # compiles ok
 
 Another form of code expression is the I<pattern code expression>.
@@ -2694,8 +2697,9 @@ Ha! Try that with your garden variety regexp package...
 
 Note that the variables C<$z0> and C<$z1> are not substituted when the
 regexp is compiled, as happens for ordinary variables outside a code
-expression.  Rather, the code expressions are evaluated when Perl
-encounters them during the search for a match.
+expression.  Rather, the whole code block is parsed as perl code at the
+same time as perl is compiling the code containing the literal regexp
+pattern.
 
 The regexp without the C<//x> modifier is
 
@@ -2727,8 +2731,8 @@ groups or produce results, it may be necessary to use this in
 combination with embedded code.
 
    %count = ();
-   "supercalifragilisticexpialidoceous" =~
-       /([aeiou])(?{ $count{$1}++; })(*FAIL)/oi;
+   "supercalifragilisticexpialidocious" =~
+       /([aeiou])(?{ $count{$1}++; })(*FAIL)/i;
    printf "%3d '%s'\n", $count{$_}, $_ for (sort keys %count);
 
 The pattern begins with a class matching a subset of letters.  Whenever
@@ -2740,7 +2744,7 @@ for another vowel. Thus, match or no match makes no difference, and the
 regexp engine proceeds until the entire string has been inspected.
 (It's remarkable that an alternative solution using something like
 
-   $count{lc($_)}++ for split('', "supercalifragilisticexpialidoceous");
+   $count{lc($_)}++ for split('', "supercalifragilisticexpialidocious");
    printf "%3d '%s'\n", $count2{$_}, $_ for ( qw{ a e i o u } );
 
 is considerably slower.)
@@ -2769,8 +2773,10 @@ the end of the block enclosing the pragmas.
     use re '/m';  # or any other flags
     $multiline_string =~ /^foo/; # /m is implied
 
-The C<re '/flags'> pragma turns on the given regular expression flags
-until the end of the lexical scope.  See C<re/"'/flags' mode"> for more
+The C<re '/flags'> pragma (introduced in Perl
+5.14) turns on the given regular expression flags
+until the end of the lexical scope.  See
+L<re/"'E<sol>flags' mode"> for more
 detail.
 
     use re 'debug';
@@ -2786,7 +2792,7 @@ information is displayed in color on terminals that can display
 termcap color sequences.  Here is example output:
 
     % perl -e 'use re "debug"; "abc" =~ /a*b+c/;'
-    Compiling REx `a*b+c'
+    Compiling REx 'a*b+c'
     size 9 first at 1
        1: STAR(4)
        2:   EXACT <a>(0)
@@ -2794,11 +2800,11 @@ termcap color sequences.  Here is example output:
        5:   EXACT <b>(0)
        7: EXACT <c>(9)
        9: END(0)
-    floating `bc' at 0..2147483647 (checking floating) minlen 2
-    Guessing start of match, REx `a*b+c' against `abc'...
-    Found floating substr `bc' at offset 1...
+    floating 'bc' at 0..2147483647 (checking floating) minlen 2
+    Guessing start of match, REx 'a*b+c' against 'abc'...
+    Found floating substr 'bc' at offset 1...
     Guessed: match at offset 0
-    Matching REx `a*b+c' against `abc'
+    Matching REx 'a*b+c' against 'abc'
       Setting an EVAL scope, savestack=3
        0 <> <abc>             |  1:  STAR
                                EXACT <a> can match 1 times out of 32767...
@@ -2809,13 +2815,13 @@ termcap color sequences.  Here is example output:
        2 <ab> <c>             |  7:      EXACT <c>
        3 <abc> <>             |  9:      END
     Match successful!
-    Freeing REx: `a*b+c'
+    Freeing REx: 'a*b+c'
 
 If you have gotten this far into the tutorial, you can probably guess
 what the different parts of the debugging output tell you.  The first
 part
 
-    Compiling REx `a*b+c'
+    Compiling REx 'a*b+c'
     size 9 first at 1
        1: STAR(4)
        2:   EXACT <a>(0)
@@ -2829,15 +2835,15 @@ starred object, in this case C<'a'>, and if it matches, goto line 4,
 i.e., C<PLUS(7)>.  The middle lines describe some heuristics and
 optimizations performed before a match:
 
-    floating `bc' at 0..2147483647 (checking floating) minlen 2
-    Guessing start of match, REx `a*b+c' against `abc'...
-    Found floating substr `bc' at offset 1...
+    floating 'bc' at 0..2147483647 (checking floating) minlen 2
+    Guessing start of match, REx 'a*b+c' against 'abc'...
+    Found floating substr 'bc' at offset 1...
     Guessed: match at offset 0
 
 Then the match is executed and the remaining lines describe the
 process:
 
-    Matching REx `a*b+c' against `abc'
+    Matching REx 'a*b+c' against 'abc'
       Setting an EVAL scope, savestack=3
        0 <> <abc>             |  1:  STAR
                                EXACT <a> can match 1 times out of 32767...
@@ -2848,12 +2854,12 @@ process:
        2 <ab> <c>             |  7:      EXACT <c>
        3 <abc> <>             |  9:      END
     Match successful!
-    Freeing REx: `a*b+c'
+    Freeing REx: 'a*b+c'
 
 Each step is of the form S<C<< n <x> <y> >>>, with C<< <x> >> the
 part of the string matched and C<< <y> >> the part not yet
 matched.  The S<C<< |  1:  STAR >>> says that Perl is at line number 1
-n the compilation list above.  See
+in the compilation list above.  See
 L<perldebguts/"Debugging Regular Expressions"> for much more detail.
 
 An alternative method of debugging regexps is to embed C<print>