]> perl5.git.perl.org Git - perl5.git/blob - lib/utf8.pm This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
perlrecharclass: minor clean-up of "Extended Bracketed Character Classes"
[perl5.git] / lib / utf8.pm
1 package utf8;
2
3 use strict;
4 use warnings;
5
6 our $utf8_hint_bits  = 0x00800000;
7 our $ascii_hint_bits = 0x00000010;  # Turned off when utf8 turned on
8
9 our $VERSION = '1.27';
10 our $AUTOLOAD;
11
12 sub import {
13     $^H |= $utf8_hint_bits;
14     $^H &= ~$ascii_hint_bits;
15 }
16
17 sub unimport {
18     $^H &= ~$utf8_hint_bits;
19 }
20
21 sub AUTOLOAD {
22     goto &$AUTOLOAD if defined &$AUTOLOAD;
23     require Carp;
24     Carp::croak("Undefined subroutine $AUTOLOAD called");
25 }
26
27 1;
28 __END__
29
30 =head1 NAME
31
32 utf8 - Perl pragma to enable/disable UTF-8 (or UTF-EBCDIC) in source code
33
34 =head1 SYNOPSIS
35
36  use utf8;
37  no utf8;
38
39  # Convert the internal representation of a Perl scalar to/from UTF-8.
40
41  $num_octets = utf8::upgrade($string);
42  $success    = utf8::downgrade($string[, $fail_ok]);
43
44  # Change each character of a Perl scalar to/from a series of
45  # characters that represent the UTF-8 bytes of each original character.
46
47  utf8::encode($string);  # "\x{100}"  becomes "\xc4\x80"
48  utf8::decode($string);  # "\xc4\x80" becomes "\x{100}"
49
50  # Convert a code point from the platform native character set to
51  # Unicode, and vice-versa.
52  $unicode = utf8::native_to_unicode(ord('A')); # returns 65 on both
53                                                # ASCII and EBCDIC
54                                                # platforms
55  $native = utf8::unicode_to_native(65);        # returns 65 on ASCII
56                                                # platforms; 193 on
57                                                # EBCDIC
58
59  $flag = utf8::is_utf8($string); # since Perl 5.8.1
60  $flag = utf8::valid($string);
61
62 =head1 DESCRIPTION
63
64 The C<use utf8> pragma tells the Perl parser to allow UTF-8 in the
65 program text in the current lexical scope.  The C<no utf8> pragma tells Perl
66 to switch back to treating the source text as literal bytes in the current
67 lexical scope.  (On EBCDIC platforms, technically it is allowing UTF-EBCDIC,
68 and not UTF-8, but this distinction is academic, so in this document the term
69 UTF-8 is used to mean both).
70
71 B<Do not use this pragma for anything else than telling Perl that your
72 script is written in UTF-8.> The utility functions described below are
73 directly usable without C<use utf8;>.
74
75 Because it is not possible to reliably tell UTF-8 from native 8 bit
76 encodings, you need either a Byte Order Mark at the beginning of your
77 source code, or C<use utf8;>, to instruct perl.
78
79 When UTF-8 becomes the standard source format, this pragma will
80 effectively become a no-op.
81
82 See also the effects of the C<-C> switch and its cousin, the
83 C<PERL_UNICODE> environment variable, in L<perlrun>.
84
85 Enabling the C<utf8> pragma has the following effect:
86
87 =over 4
88
89 =item *
90
91 Bytes in the source text that are not in the ASCII character set will be
92 treated as being part of a literal UTF-8 sequence.  This includes most
93 literals such as identifier names, string constants, and constant
94 regular expression patterns.
95
96 =back
97
98 Note that if you have non-ASCII, non-UTF-8 bytes in your script (for example
99 embedded Latin-1 in your string literals), C<use utf8> will be unhappy.  If
100 you want to have such bytes under C<use utf8>, you can disable this pragma
101 until the end the block (or file, if at top level) by C<no utf8;>.
102
103 =head2 Utility functions
104
105 The following functions are defined in the C<utf8::> package by the
106 Perl core.  You do not need to say C<use utf8> to use these and in fact
107 you should not say that unless you really want to have UTF-8 source code.
108
109 =over 4
110
111 =item * C<$num_octets = utf8::upgrade($string)>
112
113 (Since Perl v5.8.0)
114 Converts in-place the internal representation of the string from an octet
115 sequence in the native encoding (Latin-1 or EBCDIC) to UTF-8. The
116 logical character sequence itself is unchanged.  If I<$string> is already
117 upgraded, then this is a no-op. Returns the
118 number of octets necessary to represent the string as UTF-8.
119 Since Perl v5.38, if C<$string> is C<undef> no action is taken; prior to that,
120 it would be converted to be defined and zero-length.
121
122 If your code needs to be compatible with versions of perl without
123 C<use feature 'unicode_strings';>, you can force Unicode semantics on
124 a given string:
125
126   # force unicode semantics for $string without the
127   # "unicode_strings" feature
128   utf8::upgrade($string);
129
130 For example:
131
132   # without explicit or implicit use feature 'unicode_strings'
133   my $x = "\xDF";    # LATIN SMALL LETTER SHARP S
134   $x =~ /ss/i;       # won't match
135   my $y = uc($x);    # won't convert
136   utf8::upgrade($x);
137   $x =~ /ss/i;       # matches
138   my $z = uc($x);    # converts to "SS"
139
140 B<Note that this function does not handle arbitrary encodings>;
141 use L<Encode> instead.
142
143 =item * C<$success = utf8::downgrade($string[, $fail_ok])>
144
145 (Since Perl v5.8.0)
146 Converts in-place the internal representation of the string from UTF-8 to the
147 equivalent octet sequence in the native encoding (Latin-1 or EBCDIC). The
148 logical character sequence itself is unchanged. If I<$string> is already
149 stored as native 8 bit, then this is a no-op.  Can be used to make sure that
150 the UTF-8 flag is off, e.g. when you want to make sure that the substr() or
151 length() function works with the usually faster byte algorithm.
152
153 Fails if the original UTF-8 sequence cannot be represented in the
154 native 8 bit encoding. On failure dies or, if the value of I<$fail_ok> is
155 true, returns false. 
156
157 Returns true on success.
158
159 If your code expects an octet sequence this can be used to validate
160 that you've received one:
161
162   # throw an exception if not representable as octets
163   utf8::downgrade($string)
164
165   # or do your own error handling
166   utf8::downgrade($string, 1) or die "string must be octets";
167
168 B<Note that this function does not handle arbitrary encodings>;
169 use L<Encode> instead.
170
171 =item * C<utf8::encode($string)>
172
173 (Since Perl v5.8.0)
174 Converts in-place the character sequence to the corresponding octet
175 sequence in Perl's extended UTF-8. That is, every (possibly wide) character
176 gets replaced with a sequence of one or more characters that represent the
177 individual UTF-8 bytes of the character.  The UTF8 flag is turned off.
178 Returns nothing.
179
180  my $x = "\x{100}"; # $x contains one character, with ord 0x100
181  utf8::encode($x);  # $x contains two characters, with ords (on
182                     # ASCII platforms) 0xc4 and 0x80.  On EBCDIC
183                     # 1047, this would instead be 0x8C and 0x41.
184
185 Similar to:
186
187   use Encode;
188   $x = Encode::encode("utf8", $x);
189
190 B<Note that this function does not handle arbitrary encodings>;
191 use L<Encode> instead.
192
193 =item * C<$success = utf8::decode($string)>
194
195 (Since Perl v5.8.0)
196 Attempts to convert in-place the octet sequence encoded in Perl's extended
197 UTF-8 to the corresponding character sequence. That is, it replaces each
198 sequence of characters in the string whose ords represent a valid (extended)
199 UTF-8 byte sequence, with the corresponding single character.  The UTF-8 flag
200 is turned on only if the source string contains multiple-byte UTF-8
201 characters.  If I<$string> is invalid as extended UTF-8, returns false;
202 otherwise returns true.
203
204  my $x = "\xc4\x80"; # $x contains two characters, with ords
205                      # 0xc4 and 0x80
206  utf8::decode($x);   # On ASCII platforms, $x contains one char,
207                      # with ord 0x100.   Since these bytes aren't
208                      # legal UTF-EBCDIC, on EBCDIC platforms, $x is
209                      # unchanged and the function returns FALSE.
210  my $y = "\xc3\x83\xc2\xab"; This has been encoded twice; this
211                      # example is only for ASCII platforms
212  utf8::decode($y);   # Converts $y to \xc3\xab, returns TRUE;
213  utf8::decode($y);   # Further converts to \xeb, returns TRUE;
214  utf8::decode($y);   # Returns FALSE, leaves $y unchanged
215
216 B<Note that this function does not handle arbitrary encodings>;
217 use L<Encode> instead.
218
219 =item * C<$unicode = utf8::native_to_unicode($code_point)>
220
221 (Since Perl v5.8.0)
222 This takes an unsigned integer (which represents the ordinal number of a
223 character (or a code point) on the platform the program is being run on) and
224 returns its Unicode equivalent value.  Since ASCII platforms natively use the
225 Unicode code points, this function returns its input on them.  On EBCDIC
226 platforms it converts from EBCDIC to Unicode.
227
228 A meaningless value will currently be returned if the input is not an unsigned
229 integer.
230
231 Since Perl v5.22.0, calls to this function are optimized out on ASCII
232 platforms, so there is no performance hit in using it there.
233
234 =item * C<$native = utf8::unicode_to_native($code_point)>
235
236 (Since Perl v5.8.0)
237 This is the inverse of C<utf8::native_to_unicode()>, converting the other
238 direction.  Again, on ASCII platforms, this returns its input, but on EBCDIC
239 platforms it will find the native platform code point, given any Unicode one.
240
241 A meaningless value will currently be returned if the input is not an unsigned
242 integer.
243
244 Since Perl v5.22.0, calls to this function are optimized out on ASCII
245 platforms, so there is no performance hit in using it there.
246
247 =item * C<$flag = utf8::is_utf8($string)>
248
249 (Since Perl 5.8.1)  Test whether I<$string> is marked internally as encoded in
250 UTF-8.  Functionally the same as C<Encode::is_utf8($string)>.
251
252 Typically only necessary for debugging and testing, if you need to
253 dump the internals of an SV, L<Devel::Peek's|Devel::Peek> Dump()
254 provides more detail in a compact form.
255
256 If you still think you need this outside of debugging, testing or
257 dealing with filenames, you should probably read L<perlunitut> and
258 L<perlunifaq/What is "the UTF8 flag"?>.
259
260 Don't use this flag as a marker to distinguish character and binary
261 data: that should be decided for each variable when you write your
262 code.
263
264 To force unicode semantics in code portable to perl 5.8 and 5.10, call
265 C<utf8::upgrade($string)> unconditionally.
266
267 =item * C<$flag = utf8::valid($string)>
268
269 [INTERNAL] Test whether I<$string> is in a consistent state regarding
270 UTF-8.  Will return true if it is well-formed Perl extended UTF-8 and has the
271 UTF-8 flag
272 on B<or> if I<$string> is held as bytes (both these states are 'consistent').
273 The main reason for this routine is to allow Perl's test suite to check
274 that operations have left strings in a consistent state.
275
276 =back
277
278 C<utf8::encode> is like C<utf8::upgrade>, but the UTF8 flag is
279 cleared.  See L<perlunicode>, and the C API
280 functions C<L<sv_utf8_upgrade|perlapi/sv_utf8_upgrade>>,
281 C<L<perlapi/sv_utf8_downgrade>>, C<L<perlapi/sv_utf8_encode>>,
282 and C<L<perlapi/sv_utf8_decode>>, which are wrapped by the Perl functions
283 C<utf8::upgrade>, C<utf8::downgrade>, C<utf8::encode> and
284 C<utf8::decode>.  Also, the functions C<utf8::is_utf8>, C<utf8::valid>,
285 C<utf8::encode>, C<utf8::decode>, C<utf8::upgrade>, and C<utf8::downgrade> are
286 actually internal, and thus always available, without a C<require utf8>
287 statement.
288
289 =head1 BUGS
290
291 Some filesystems may not support UTF-8 file names, or they may be supported
292 incompatibly with Perl.  Therefore UTF-8 names that are visible to the
293 filesystem, such as module names may not work.
294
295 =head1 SEE ALSO
296
297 L<perlunitut>, L<perluniintro>, L<perlrun>, L<bytes>, L<perlunicode>
298
299 =cut