1 # $Id: encoding.pm,v 2.3 2006/05/03 18:24:10 dankogai Exp $
3 our $VERSION = do { my @r = ( q$Revision: 2.3 $ =~ /\d+/g ); sprintf "%d." . "%02d" x $#r, @r };
11 if ( ord("A") == 193 ) {
13 Carp::croak("encoding: pragma does not support EBCDIC platforms");
18 eval { require PerlIO::encoding };
20 $HAS_PERLIO = ( PerlIO::encoding->VERSION >= 0.02 );
25 $] > 5.008 and return 0; # 5.8.1 or higher then no
26 my %utfs = map { $_ => 1 }
27 qw(utf8 UCS-2BE UCS-2LE UTF-16 UTF-16BE UTF-16LE
28 UTF-32 UTF-32BE UTF-32LE);
29 $utfs{$name} or return 0; # UTFs or no
33 return $Config{perl_patchlevel} ? 0 : 1 # maintperl then no
36 sub in_locale { $^H & ( $locale::hint_bits || 0 ) }
38 sub _get_locale_encoding {
41 # I18N::Langinfo isn't available everywhere
43 require I18N::Langinfo;
44 I18N::Langinfo->import(qw(langinfo CODESET));
45 $locale_encoding = langinfo( CODESET() );
50 no warnings 'uninitialized';
52 if ( not $locale_encoding && in_locale() ) {
53 if ( $ENV{LC_ALL} =~ /^([^.]+)\.([^.]+)$/ ) {
54 ( $country_language, $locale_encoding ) = ( $1, $2 );
56 elsif ( $ENV{LANG} =~ /^([^.]+)\.([^.]+)$/ ) {
57 ( $country_language, $locale_encoding ) = ( $1, $2 );
60 # LANGUAGE affects only LC_MESSAGES only on glibc
62 elsif ( not $locale_encoding ) {
63 if ( $ENV{LC_ALL} =~ /\butf-?8\b/i
64 || $ENV{LANG} =~ /\butf-?8\b/i )
66 $locale_encoding = 'utf8';
69 # Could do more heuristics based on the country and language
70 # parts of LC_ALL and LANG (the parts before the dot (if any)),
71 # since we have Locale::Country and Locale::Language available.
72 # TODO: get a database of Language -> Encoding mappings
73 # (the Estonian database at http://www.eki.ee/letter/
74 # would be excellent!) --jhi
76 if ( defined $locale_encoding
77 && lc($locale_encoding) eq 'euc'
78 && defined $country_language )
80 if ( $country_language =~ /^ja_JP|japan(?:ese)?$/i ) {
81 $locale_encoding = 'euc-jp';
83 elsif ( $country_language =~ /^ko_KR|korean?$/i ) {
84 $locale_encoding = 'euc-kr';
86 elsif ( $country_language =~ /^zh_CN|chin(?:a|ese)$/i ) {
87 $locale_encoding = 'euc-cn';
89 elsif ( $country_language =~ /^zh_TW|taiwan(?:ese)?$/i ) {
90 $locale_encoding = 'euc-tw';
95 "encoding: Locale encoding '$locale_encoding' too ambiguous"
100 return $locale_encoding;
106 if ( $name eq ':_get_locale_encoding' ) { # used by lib/open.pm
107 my $caller = caller();
110 *{"${caller}::_get_locale_encoding"} = \&_get_locale_encoding;
114 $name = _get_locale_encoding() if $name eq ':locale';
116 $name = $ENV{PERL_ENCODING} unless defined $name;
117 my $enc = find_encoding($name);
118 unless ( defined $enc ) {
120 Carp::croak("encoding: Unknown encoding '$name'");
122 $name = $enc->name; # canonize
123 unless ( $arg{Filter} ) {
124 DEBUG and warn "_exception($name) = ", _exception($name);
125 _exception($name) or ${^ENCODING} = $enc;
126 $HAS_PERLIO or return 1;
129 defined( ${^ENCODING} ) and undef ${^ENCODING};
131 # implicitly 'use utf8'
132 require utf8; # to fetch $utf8::hint_bits;
133 $^H |= $utf8::hint_bits;
135 require Filter::Util::Call;
136 Filter::Util::Call->import;
139 my $status = filter_read();
141 $_ = $enc->decode( $_, 1 );
148 $@ eq '' and DEBUG and warn "Filter installed";
150 defined ${^UNICODE} and ${^UNICODE} != 0 and return 1;
151 for my $h (qw(STDIN STDOUT)) {
153 unless ( defined find_encoding( $arg{$h} ) ) {
156 "encoding: Unknown encoding for $h, '$arg{$h}'");
158 eval { binmode( $h, ":raw :encoding($arg{$h})" ) };
161 unless ( exists $arg{$h} ) {
163 no warnings 'uninitialized';
164 binmode( $h, ":raw :encoding($name)" );
173 return 1; # I doubt if we need it, though
180 binmode( STDIN, ":raw" );
181 binmode( STDOUT, ":raw" );
187 if ( $INC{"Filter/Util/Call.pm"} ) {
188 eval { filter_del() };
199 encoding - allows you to write your script in non-ascii or non-utf8
203 use encoding "greek"; # Perl like Greek to you?
204 use encoding "euc-jp"; # Jperl!
206 # or you can even do this if your shell supports your native encoding
208 perl -Mencoding=latin2 -e '...' # Feeling centrally European?
209 perl -Mencoding=euc-kr -e '...' # Or Korean?
213 # A simple euc-cn => utf-8 converter
214 use encoding "euc-cn", STDOUT => "utf8"; while(<>){print};
216 # "no encoding;" supported (but not scoped!)
219 # an alternate way, Filter
220 use encoding "euc-jp", Filter=>1;
221 # now you can use kanji identifiers -- in euc-jp!
224 # note that this probably means that unless you have a complete control
225 # over the environments the application is ever going to be run, you should
226 # NOT use the feature of encoding pragma allowing you to write your script
227 # in any recognized encoding because changing locale settings will wreck
228 # the script; you can of course still use the other features of the pragma.
229 use encoding ':locale';
233 Let's start with a bit of history: Perl 5.6.0 introduced Unicode
234 support. You could apply C<substr()> and regexes even to complex CJK
235 characters -- so long as the script was written in UTF-8. But back
236 then, text editors that supported UTF-8 were still rare and many users
237 instead chose to write scripts in legacy encodings, giving up a whole
238 new feature of Perl 5.6.
240 Rewind to the future: starting from perl 5.8.0 with the B<encoding>
241 pragma, you can write your script in any encoding you like (so long
242 as the C<Encode> module supports it) and still enjoy Unicode support.
243 This pragma achieves that by doing the following:
249 Internally converts all literals (C<q//,qq//,qr//,qw///, qx//>) from
250 the encoding specified to utf8. In Perl 5.8.1 and later, literals in
251 C<tr///> and C<DATA> pseudo-filehandle are also converted.
255 Changing PerlIO layers of C<STDIN> and C<STDOUT> to the encoding
260 =head2 Literal Conversions
262 You can write code in EUC-JP as follows:
264 my $Rakuda = "\xF1\xD1\xF1\xCC"; # Camel in Kanji
265 #<-char-><-char-> # 4 octets
266 s/\bCamel\b/$Rakuda/;
268 And with C<use encoding "euc-jp"> in effect, it is the same thing as
271 my $Rakuda = "\x{99F1}\x{99DD}"; # two Unicode Characters
272 s/\bCamel\b/$Rakuda/;
274 =head2 PerlIO layers for C<STD(IN|OUT)>
276 The B<encoding> pragma also modifies the filehandle layers of
277 STDIN and STDOUT to the specified encoding. Therefore,
279 use encoding "euc-jp";
280 my $message = "Camel is the symbol of perl.\n";
281 my $Rakuda = "\xF1\xD1\xF1\xCC"; # Camel in Kanji
282 $message =~ s/\bCamel\b/$Rakuda/;
285 Will print "\xF1\xD1\xF1\xCC is the symbol of perl.\n",
286 not "\x{99F1}\x{99DD} is the symbol of perl.\n".
288 You can override this by giving extra arguments; see below.
290 =head2 Implicit upgrading for byte strings
292 By default, if strings operating under byte semantics and strings
293 with Unicode character data are concatenated, the new string will
294 be created by decoding the byte strings as I<ISO 8859-1 (Latin-1)>.
296 The B<encoding> pragma changes this to use the specified encoding
297 instead. For example:
300 my $string = chr(20000); # a Unicode string
301 utf8::encode($string); # now it's a UTF-8 encoded byte string
302 # concatenate with another Unicode string
303 print length($string . chr(20000));
305 Will print C<2>, because C<$string> is upgraded as UTF-8. Without
306 C<use encoding 'utf8';>, it will print C<4> instead, since C<$string>
307 is three octets when interpreted as Latin-1.
309 =head1 FEATURES THAT REQUIRE 5.8.1
311 Some of the features offered by this pragma requires perl 5.8.1. Most
312 of these are done by Inaba Hiroto. Any other features and changes
317 =item "NON-EUC" doublebyte encodings
319 Because perl needs to parse script before applying this pragma, such
320 encodings as Shift_JIS and Big-5 that may contain '\' (BACKSLASH;
321 \x5c) in the second byte fails because the second byte may
322 accidentally escape the quoting character that follows. Perl 5.8.1
323 or later fixes this problem.
327 C<tr//> was overlooked by Perl 5 porters when they released perl 5.8.0
328 See the section below for details.
330 =item DATA pseudo-filehandle
332 Another feature that was overlooked was C<DATA>.
340 =item use encoding [I<ENCNAME>] ;
342 Sets the script encoding to I<ENCNAME>. And unless ${^UNICODE}
343 exists and non-zero, PerlIO layers of STDIN and STDOUT are set to
344 ":encoding(I<ENCNAME>)".
346 Note that STDERR WILL NOT be changed.
348 Also note that non-STD file handles remain unaffected. Use C<use
349 open> or C<binmode> to change layers of those.
351 If no encoding is specified, the environment variable L<PERL_ENCODING>
352 is consulted. If no encoding can be found, the error C<Unknown encoding
353 'I<ENCNAME>'> will be thrown.
355 =item use encoding I<ENCNAME> [ STDIN =E<gt> I<ENCNAME_IN> ...] ;
357 You can also individually set encodings of STDIN and STDOUT via the
358 C<< STDIN => I<ENCNAME> >> form. In this case, you cannot omit the
359 first I<ENCNAME>. C<< STDIN => undef >> turns the IO transcoding
362 When ${^UNICODE} exists and non-zero, these options will completely
363 ignored. ${^UNICODE} is a variable introduced in perl 5.8.1. See
364 L<perlrun> see L<perlvar/"${^UNICODE}"> and L<perlrun/"-C"> for
365 details (perl 5.8.1 and later).
367 =item use encoding I<ENCNAME> Filter=E<gt>1;
369 This turns the encoding pragma into a source filter. While the
370 default approach just decodes interpolated literals (in qq() and
371 qr()), this will apply a source filter to the entire source code. See
372 L</"The Filter Option"> below for details.
376 Unsets the script encoding. The layers of STDIN, STDOUT are
377 reset to ":raw" (the default unprocessed raw stream of bytes).
381 =head1 The Filter Option
383 The magic of C<use encoding> is not applied to the names of
384 identifiers. In order to make C<${"\x{4eba}"}++> ($human++, where human
385 is a single Han ideograph) work, you still need to write your script
386 in UTF-8 -- or use a source filter. That's what 'Filter=>1' does.
388 What does this mean? Your source code behaves as if it is written in
389 UTF-8 with 'use utf8' in effect. So even if your editor only supports
390 Shift_JIS, for example, you can still try examples in Chapter 15 of
391 C<Programming Perl, 3rd Ed.>. For instance, you can use UTF-8
394 This option is significantly slower and (as of this writing) non-ASCII
395 identifiers are not very stable WITHOUT this option and with the
396 source code written in UTF-8.
398 =head2 Filter-related changes at Encode version 1.87
404 The Filter option now sets STDIN and STDOUT like non-filter options.
405 And C<< STDIN=>I<ENCODING> >> and C<< STDOUT=>I<ENCODING> >> work like
410 C<use utf8> is implicitly declared so you no longer have to C<use
411 utf8> to C<${"\x{4eba}"}++>.
419 The pragma is a per script, not a per block lexical. Only the last
420 C<use encoding> or C<no encoding> matters, and it affects
421 B<the whole script>. However, the <no encoding> pragma is supported and
422 B<use encoding> can appear as many times as you want in a given script.
423 The multiple use of this pragma is discouraged.
425 By the same reason, the use this pragma inside modules is also
426 discouraged (though not as strongly discouraged as the case above.
429 If you still have to write a module with this pragma, be very careful
430 of the load order. See the codes below;
433 package Module_IN_BAR;
435 # stuff in "bar" encoding here
441 # surprise! use encoding "bar" is in effect.
443 The best way to avoid this oddity is to use this pragma RIGHT AFTER
444 other modules are loaded. i.e.
449 =head2 DO NOT MIX MULTIPLE ENCODINGS
451 Notice that only literals (string or regular expression) having only
452 legacy code points are affected: if you mix data like this
456 the data is assumed to be in (Latin 1 and) Unicode, not in your native
457 encoding. In other words, this will match in "greek":
463 "\xDF\x{100}" =~ /\x{3af}\x{100}/
465 since the C<\xDF> (ISO 8859-7 GREEK SMALL LETTER IOTA WITH TONOS) on
466 the left will B<not> be upgraded to C<\x{3af}> (Unicode GREEK SMALL
467 LETTER IOTA WITH TONOS) because of the C<\x{100}> on the left. You
468 should not be mixing your legacy data and Unicode in the same string.
470 This pragma also affects encoding of the 0x80..0xFF code point range:
471 normally characters in that range are left as eight-bit bytes (unless
472 they are combined with characters with code points 0x100 or larger,
473 in which case all characters need to become UTF-8 encoded), but if
474 the C<encoding> pragma is present, even the 0x80..0xFF range always
477 After all, the best thing about this pragma is that you don't have to
478 resort to \x{....} just to spell your name in a native encoding.
479 So feel free to put your strings in your encoding in quotes and
482 =head2 tr/// with ranges
484 The B<encoding> pragma works by decoding string literals in
485 C<q//,qq//,qr//,qw///, qx//> and so forth. In perl 5.8.0, this
486 does not apply to C<tr///>. Therefore,
488 use encoding 'euc-jp';
490 $kana =~ tr/\xA4\xA1-\xA4\xF3/\xA5\xA1-\xA5\xF3/;
491 # -------- -------- -------- --------
495 $kana =~ tr/\x{3041}-\x{3093}/\x{30a1}-\x{30f3}/;
499 =item Legend of characters above
501 utf8 euc-jp charnames::viacode()
502 -----------------------------------------
503 \x{3041} \xA4\xA1 HIRAGANA LETTER SMALL A
504 \x{3093} \xA4\xF3 HIRAGANA LETTER N
505 \x{30a1} \xA5\xA1 KATAKANA LETTER SMALL A
506 \x{30f3} \xA5\xF3 KATAKANA LETTER N
510 This counterintuitive behavior has been fixed in perl 5.8.1.
512 =head3 workaround to tr///;
514 In perl 5.8.0, you can work around as follows;
516 use encoding 'euc-jp';
518 eval qq{ \$kana =~ tr/\xA4\xA1-\xA4\xF3/\xA5\xA1-\xA5\xF3/ };
520 Note the C<tr//> expression is surrounded by C<qq{}>. The idea behind
521 is the same as classic idiom that makes C<tr///> 'interpolate'.
523 tr/$from/$to/; # wrong!
524 eval qq{ tr/$from/$to/ }; # workaround.
526 Nevertheless, in case of B<encoding> pragma even C<q//> is affected so
527 C<tr///> not being decoded was obviously against the will of Perl5
528 Porters so it has been fixed in Perl 5.8.1 or later.
530 =head1 EXAMPLE - Greekperl
532 use encoding "iso 8859-7";
534 # \xDF in ISO 8859-7 (Greek) is \x{3af} in Unicode.
539 printf "%#x\n", ord($a); # will print 0x3af, not 0xdf
543 # $c will be "\x{3af}\x{100}", not "\x{df}\x{100}".
545 # chr() is affected, and ...
547 print "mega\n" if ord(chr(0xdf)) == 0x3af;
549 # ... ord() is affected by the encoding pragma ...
551 print "tera\n" if ord(pack("C", 0xdf)) == 0x3af;
553 # ... as are eq and cmp ...
555 print "peta\n" if "\x{3af}" eq pack("C", 0xdf);
556 print "exa\n" if "\x{3af}" cmp pack("C", 0xdf) == 0;
558 # ... but pack/unpack C are not affected, in case you still
559 # want to go back to your native encoding
561 print "zetta\n" if unpack("C", (pack("C", 0xdf))) == 0xdf;
563 =head1 KNOWN PROBLEMS
567 =item literals in regex that are longer than 127 bytes
569 For native multibyte encodings (either fixed or variable length),
570 the current implementation of the regular expressions may introduce
571 recoding errors for regular expression literals longer than 127 bytes.
575 The encoding pragma is not supported on EBCDIC platforms.
576 (Porters who are willing and able to remove this limitation are
581 This pragma doesn't work well with format because PerlIO does not
582 get along very well with it. When format contains non-ascii
583 characters it prints funny or gets "wide character warnings".
584 To understand it, try the code below.
586 # Save this one in utf8
587 # replace *non-ascii* with a non-ascii string
593 $camel = "*non-ascii*";
594 binmode(STDOUT=>':encoding(utf8)'); # bang!
596 print $camel, "\n"; # fine
598 Without binmode this happens to work but without binmode, print()
599 fails instead of write().
601 At any rate, the very use of format is questionable when it comes to
602 unicode characters since you have to consider such things as character
603 width (i.e. double-width for ideographs) and directions (i.e. BIDI for
608 =head2 The Logic of :locale
610 The logic of C<:locale> is as follows:
616 If the platform supports the langinfo(CODESET) interface, the codeset
617 returned is used as the default encoding for the open pragma.
621 If 1. didn't work but we are under the locale pragma, the environment
622 variables LC_ALL and LANG (in that order) are matched for encodings
623 (the part after C<.>, if any), and if any found, that is used
624 as the default encoding for the open pragma.
628 If 1. and 2. didn't work, the environment variables LC_ALL and LANG
629 (in that order) are matched for anything looking like UTF-8, and if
630 any found, C<:utf8> is used as the default encoding for the open
635 If your locale environment variables (LC_ALL, LC_CTYPE, LANG)
636 contain the strings 'UTF-8' or 'UTF8' (case-insensitive matching),
637 the default encoding of your STDIN, STDOUT, and STDERR, and of
638 B<any subsequent file open>, is UTF-8.
642 This pragma first appeared in Perl 5.8.0. For features that require
643 5.8.1 and better, see above.
645 The C<:locale> subpragma was implemented in 2.01, or Perl 5.8.6.
649 L<perlunicode>, L<Encode>, L<open>, L<Filter::Util::Call>,
651 Ch. 15 of C<Programming Perl (3rd Edition)>
652 by Larry Wall, Tom Christiansen, Jon Orwant;
653 O'Reilly & Associates; ISBN 0-596-00027-8