1 # $Id: encoding.pm,v 2.6 2007/04/22 14:56:12 dankogai Exp $
3 our $VERSION = '2.6_01';
12 if ( ord("A") == 193 ) {
14 Carp::croak("encoding: pragma does not support EBCDIC platforms");
19 eval { require PerlIO::encoding };
21 $HAS_PERLIO = ( PerlIO::encoding->VERSION >= 0.02 );
26 $] > 5.008 and return 0; # 5.8.1 or higher then no
27 my %utfs = map { $_ => 1 }
28 qw(utf8 UCS-2BE UCS-2LE UTF-16 UTF-16BE UTF-16LE
29 UTF-32 UTF-32BE UTF-32LE);
30 $utfs{$name} or return 0; # UTFs or no
34 return $Config{perl_patchlevel} ? 0 : 1 # maintperl then no
37 sub in_locale { $^H & ( $locale::hint_bits || 0 ) }
39 sub _get_locale_encoding {
42 # I18N::Langinfo isn't available everywhere
44 require I18N::Langinfo;
45 I18N::Langinfo->import(qw(langinfo CODESET));
46 $locale_encoding = langinfo( CODESET() );
51 no warnings 'uninitialized';
53 if ( not $locale_encoding && in_locale() ) {
54 if ( $ENV{LC_ALL} =~ /^([^.]+)\.([^.@]+)(@.*)?$/ ) {
55 ( $country_language, $locale_encoding ) = ( $1, $2 );
57 elsif ( $ENV{LANG} =~ /^([^.]+)\.([^.@]+)(@.*)?$/ ) {
58 ( $country_language, $locale_encoding ) = ( $1, $2 );
61 # LANGUAGE affects only LC_MESSAGES only on glibc
63 elsif ( not $locale_encoding ) {
64 if ( $ENV{LC_ALL} =~ /\butf-?8\b/i
65 || $ENV{LANG} =~ /\butf-?8\b/i )
67 $locale_encoding = 'utf8';
70 # Could do more heuristics based on the country and language
71 # parts of LC_ALL and LANG (the parts before the dot (if any)),
72 # since we have Locale::Country and Locale::Language available.
73 # TODO: get a database of Language -> Encoding mappings
74 # (the Estonian database at http://www.eki.ee/letter/
75 # would be excellent!) --jhi
77 if ( defined $locale_encoding
78 && lc($locale_encoding) eq 'euc'
79 && defined $country_language )
81 if ( $country_language =~ /^ja_JP|japan(?:ese)?$/i ) {
82 $locale_encoding = 'euc-jp';
84 elsif ( $country_language =~ /^ko_KR|korean?$/i ) {
85 $locale_encoding = 'euc-kr';
87 elsif ( $country_language =~ /^zh_CN|chin(?:a|ese)$/i ) {
88 $locale_encoding = 'euc-cn';
90 elsif ( $country_language =~ /^zh_TW|taiwan(?:ese)?$/i ) {
91 $locale_encoding = 'euc-tw';
96 "encoding: Locale encoding '$locale_encoding' too ambiguous"
101 return $locale_encoding;
107 if ( $name eq ':_get_locale_encoding' ) { # used by lib/open.pm
108 my $caller = caller();
111 *{"${caller}::_get_locale_encoding"} = \&_get_locale_encoding;
115 $name = _get_locale_encoding() if $name eq ':locale';
117 $name = $ENV{PERL_ENCODING} unless defined $name;
118 my $enc = find_encoding($name);
119 unless ( defined $enc ) {
121 Carp::croak("encoding: Unknown encoding '$name'");
123 $name = $enc->name; # canonize
124 unless ( $arg{Filter} ) {
125 DEBUG and warn "_exception($name) = ", _exception($name);
126 _exception($name) or ${^ENCODING} = $enc;
127 $HAS_PERLIO or return 1;
130 defined( ${^ENCODING} ) and undef ${^ENCODING};
132 # implicitly 'use utf8'
133 require utf8; # to fetch $utf8::hint_bits;
134 $^H |= $utf8::hint_bits;
136 require Filter::Util::Call;
137 Filter::Util::Call->import;
140 my $status = filter_read();
142 $_ = $enc->decode( $_, 1 );
149 $@ eq '' and DEBUG and warn "Filter installed";
151 defined ${^UNICODE} and ${^UNICODE} != 0 and return 1;
152 for my $h (qw(STDIN STDOUT)) {
154 unless ( defined find_encoding( $arg{$h} ) ) {
157 "encoding: Unknown encoding for $h, '$arg{$h}'");
159 eval { binmode( $h, ":raw :encoding($arg{$h})" ) };
162 unless ( exists $arg{$h} ) {
164 no warnings 'uninitialized';
165 binmode( $h, ":raw :encoding($name)" );
174 return 1; # I doubt if we need it, though
181 binmode( STDIN, ":raw" );
182 binmode( STDOUT, ":raw" );
188 if ( $INC{"Filter/Util/Call.pm"} ) {
189 eval { filter_del() };
200 encoding - allows you to write your script in non-ascii or non-utf8
204 use encoding "greek"; # Perl like Greek to you?
205 use encoding "euc-jp"; # Jperl!
207 # or you can even do this if your shell supports your native encoding
209 perl -Mencoding=latin2 -e '...' # Feeling centrally European?
210 perl -Mencoding=euc-kr -e '...' # Or Korean?
214 # A simple euc-cn => utf-8 converter
215 use encoding "euc-cn", STDOUT => "utf8"; while(<>){print};
217 # "no encoding;" supported (but not scoped!)
220 # an alternate way, Filter
221 use encoding "euc-jp", Filter=>1;
222 # now you can use kanji identifiers -- in euc-jp!
225 # note that this probably means that unless you have a complete control
226 # over the environments the application is ever going to be run, you should
227 # NOT use the feature of encoding pragma allowing you to write your script
228 # in any recognized encoding because changing locale settings will wreck
229 # the script; you can of course still use the other features of the pragma.
230 use encoding ':locale';
234 Let's start with a bit of history: Perl 5.6.0 introduced Unicode
235 support. You could apply C<substr()> and regexes even to complex CJK
236 characters -- so long as the script was written in UTF-8. But back
237 then, text editors that supported UTF-8 were still rare and many users
238 instead chose to write scripts in legacy encodings, giving up a whole
239 new feature of Perl 5.6.
241 Rewind to the future: starting from perl 5.8.0 with the B<encoding>
242 pragma, you can write your script in any encoding you like (so long
243 as the C<Encode> module supports it) and still enjoy Unicode support.
244 This pragma achieves that by doing the following:
250 Internally converts all literals (C<q//,qq//,qr//,qw///, qx//>) from
251 the encoding specified to utf8. In Perl 5.8.1 and later, literals in
252 C<tr///> and C<DATA> pseudo-filehandle are also converted.
256 Changing PerlIO layers of C<STDIN> and C<STDOUT> to the encoding
261 =head2 Literal Conversions
263 You can write code in EUC-JP as follows:
265 my $Rakuda = "\xF1\xD1\xF1\xCC"; # Camel in Kanji
266 #<-char-><-char-> # 4 octets
267 s/\bCamel\b/$Rakuda/;
269 And with C<use encoding "euc-jp"> in effect, it is the same thing as
272 my $Rakuda = "\x{99F1}\x{99DD}"; # two Unicode Characters
273 s/\bCamel\b/$Rakuda/;
275 =head2 PerlIO layers for C<STD(IN|OUT)>
277 The B<encoding> pragma also modifies the filehandle layers of
278 STDIN and STDOUT to the specified encoding. Therefore,
280 use encoding "euc-jp";
281 my $message = "Camel is the symbol of perl.\n";
282 my $Rakuda = "\xF1\xD1\xF1\xCC"; # Camel in Kanji
283 $message =~ s/\bCamel\b/$Rakuda/;
286 Will print "\xF1\xD1\xF1\xCC is the symbol of perl.\n",
287 not "\x{99F1}\x{99DD} is the symbol of perl.\n".
289 You can override this by giving extra arguments; see below.
291 =head2 Implicit upgrading for byte strings
293 By default, if strings operating under byte semantics and strings
294 with Unicode character data are concatenated, the new string will
295 be created by decoding the byte strings as I<ISO 8859-1 (Latin-1)>.
297 The B<encoding> pragma changes this to use the specified encoding
298 instead. For example:
301 my $string = chr(20000); # a Unicode string
302 utf8::encode($string); # now it's a UTF-8 encoded byte string
303 # concatenate with another Unicode string
304 print length($string . chr(20000));
306 Will print C<2>, because C<$string> is upgraded as UTF-8. Without
307 C<use encoding 'utf8';>, it will print C<4> instead, since C<$string>
308 is three octets when interpreted as Latin-1.
312 If the C<encoding> pragma is in scope then the lengths returned are
313 calculated from the length of C<$/> in Unicode characters, which is not
314 always the same as the length of C<$/> in the native encoding.
316 This pragma affects utf8::upgrade, but not utf8::downgrade.
320 If the C<encoding> pragma is in scope then the lengths returned are
321 calculated from the length of C<$/> in Unicode characters, which is not
322 always the same as the length of C<$/> in the native encoding.
324 This pragma affects utf8::upgrade, but not utf8::downgrade.
328 If the C<encoding> pragma is in scope then the lengths returned are
329 calculated from the length of C<$/> in Unicode characters, which is not
330 always the same as the length of C<$/> in the native encoding.
332 This pragma affects utf8::upgrade, but not utf8::downgrade.
334 =head1 FEATURES THAT REQUIRE 5.8.1
336 Some of the features offered by this pragma requires perl 5.8.1. Most
337 of these are done by Inaba Hiroto. Any other features and changes
342 =item "NON-EUC" doublebyte encodings
344 Because perl needs to parse script before applying this pragma, such
345 encodings as Shift_JIS and Big-5 that may contain '\' (BACKSLASH;
346 \x5c) in the second byte fails because the second byte may
347 accidentally escape the quoting character that follows. Perl 5.8.1
348 or later fixes this problem.
352 C<tr//> was overlooked by Perl 5 porters when they released perl 5.8.0
353 See the section below for details.
355 =item DATA pseudo-filehandle
357 Another feature that was overlooked was C<DATA>.
365 =item use encoding [I<ENCNAME>] ;
367 Sets the script encoding to I<ENCNAME>. And unless ${^UNICODE}
368 exists and non-zero, PerlIO layers of STDIN and STDOUT are set to
369 ":encoding(I<ENCNAME>)".
371 Note that STDERR WILL NOT be changed.
373 Also note that non-STD file handles remain unaffected. Use C<use
374 open> or C<binmode> to change layers of those.
376 If no encoding is specified, the environment variable L<PERL_ENCODING>
377 is consulted. If no encoding can be found, the error C<Unknown encoding
378 'I<ENCNAME>'> will be thrown.
380 =item use encoding I<ENCNAME> [ STDIN =E<gt> I<ENCNAME_IN> ...] ;
382 You can also individually set encodings of STDIN and STDOUT via the
383 C<< STDIN => I<ENCNAME> >> form. In this case, you cannot omit the
384 first I<ENCNAME>. C<< STDIN => undef >> turns the IO transcoding
387 When ${^UNICODE} exists and non-zero, these options will completely
388 ignored. ${^UNICODE} is a variable introduced in perl 5.8.1. See
389 L<perlrun> see L<perlvar/"${^UNICODE}"> and L<perlrun/"-C"> for
390 details (perl 5.8.1 and later).
392 =item use encoding I<ENCNAME> Filter=E<gt>1;
394 This turns the encoding pragma into a source filter. While the
395 default approach just decodes interpolated literals (in qq() and
396 qr()), this will apply a source filter to the entire source code. See
397 L</"The Filter Option"> below for details.
401 Unsets the script encoding. The layers of STDIN, STDOUT are
402 reset to ":raw" (the default unprocessed raw stream of bytes).
406 =head1 The Filter Option
408 The magic of C<use encoding> is not applied to the names of
409 identifiers. In order to make C<${"\x{4eba}"}++> ($human++, where human
410 is a single Han ideograph) work, you still need to write your script
411 in UTF-8 -- or use a source filter. That's what 'Filter=>1' does.
413 What does this mean? Your source code behaves as if it is written in
414 UTF-8 with 'use utf8' in effect. So even if your editor only supports
415 Shift_JIS, for example, you can still try examples in Chapter 15 of
416 C<Programming Perl, 3rd Ed.>. For instance, you can use UTF-8
419 This option is significantly slower and (as of this writing) non-ASCII
420 identifiers are not very stable WITHOUT this option and with the
421 source code written in UTF-8.
423 =head2 Filter-related changes at Encode version 1.87
429 The Filter option now sets STDIN and STDOUT like non-filter options.
430 And C<< STDIN=>I<ENCODING> >> and C<< STDOUT=>I<ENCODING> >> work like
435 C<use utf8> is implicitly declared so you no longer have to C<use
436 utf8> to C<${"\x{4eba}"}++>.
444 The pragma is a per script, not a per block lexical. Only the last
445 C<use encoding> or C<no encoding> matters, and it affects
446 B<the whole script>. However, the <no encoding> pragma is supported and
447 B<use encoding> can appear as many times as you want in a given script.
448 The multiple use of this pragma is discouraged.
450 By the same reason, the use this pragma inside modules is also
451 discouraged (though not as strongly discouraged as the case above.
454 If you still have to write a module with this pragma, be very careful
455 of the load order. See the codes below;
458 package Module_IN_BAR;
460 # stuff in "bar" encoding here
466 # surprise! use encoding "bar" is in effect.
468 The best way to avoid this oddity is to use this pragma RIGHT AFTER
469 other modules are loaded. i.e.
474 =head2 DO NOT MIX MULTIPLE ENCODINGS
476 Notice that only literals (string or regular expression) having only
477 legacy code points are affected: if you mix data like this
481 the data is assumed to be in (Latin 1 and) Unicode, not in your native
482 encoding. In other words, this will match in "greek":
488 "\xDF\x{100}" =~ /\x{3af}\x{100}/
490 since the C<\xDF> (ISO 8859-7 GREEK SMALL LETTER IOTA WITH TONOS) on
491 the left will B<not> be upgraded to C<\x{3af}> (Unicode GREEK SMALL
492 LETTER IOTA WITH TONOS) because of the C<\x{100}> on the left. You
493 should not be mixing your legacy data and Unicode in the same string.
495 This pragma also affects encoding of the 0x80..0xFF code point range:
496 normally characters in that range are left as eight-bit bytes (unless
497 they are combined with characters with code points 0x100 or larger,
498 in which case all characters need to become UTF-8 encoded), but if
499 the C<encoding> pragma is present, even the 0x80..0xFF range always
502 After all, the best thing about this pragma is that you don't have to
503 resort to \x{....} just to spell your name in a native encoding.
504 So feel free to put your strings in your encoding in quotes and
507 =head2 tr/// with ranges
509 The B<encoding> pragma works by decoding string literals in
510 C<q//,qq//,qr//,qw///, qx//> and so forth. In perl 5.8.0, this
511 does not apply to C<tr///>. Therefore,
513 use encoding 'euc-jp';
515 $kana =~ tr/\xA4\xA1-\xA4\xF3/\xA5\xA1-\xA5\xF3/;
516 # -------- -------- -------- --------
520 $kana =~ tr/\x{3041}-\x{3093}/\x{30a1}-\x{30f3}/;
524 =item Legend of characters above
526 utf8 euc-jp charnames::viacode()
527 -----------------------------------------
528 \x{3041} \xA4\xA1 HIRAGANA LETTER SMALL A
529 \x{3093} \xA4\xF3 HIRAGANA LETTER N
530 \x{30a1} \xA5\xA1 KATAKANA LETTER SMALL A
531 \x{30f3} \xA5\xF3 KATAKANA LETTER N
535 This counterintuitive behavior has been fixed in perl 5.8.1.
537 =head3 workaround to tr///;
539 In perl 5.8.0, you can work around as follows;
541 use encoding 'euc-jp';
543 eval qq{ \$kana =~ tr/\xA4\xA1-\xA4\xF3/\xA5\xA1-\xA5\xF3/ };
545 Note the C<tr//> expression is surrounded by C<qq{}>. The idea behind
546 is the same as classic idiom that makes C<tr///> 'interpolate'.
548 tr/$from/$to/; # wrong!
549 eval qq{ tr/$from/$to/ }; # workaround.
551 Nevertheless, in case of B<encoding> pragma even C<q//> is affected so
552 C<tr///> not being decoded was obviously against the will of Perl5
553 Porters so it has been fixed in Perl 5.8.1 or later.
555 =head1 EXAMPLE - Greekperl
557 use encoding "iso 8859-7";
559 # \xDF in ISO 8859-7 (Greek) is \x{3af} in Unicode.
564 printf "%#x\n", ord($a); # will print 0x3af, not 0xdf
568 # $c will be "\x{3af}\x{100}", not "\x{df}\x{100}".
570 # chr() is affected, and ...
572 print "mega\n" if ord(chr(0xdf)) == 0x3af;
574 # ... ord() is affected by the encoding pragma ...
576 print "tera\n" if ord(pack("C", 0xdf)) == 0x3af;
578 # ... as are eq and cmp ...
580 print "peta\n" if "\x{3af}" eq pack("C", 0xdf);
581 print "exa\n" if "\x{3af}" cmp pack("C", 0xdf) == 0;
583 # ... but pack/unpack C are not affected, in case you still
584 # want to go back to your native encoding
586 print "zetta\n" if unpack("C", (pack("C", 0xdf))) == 0xdf;
588 =head1 KNOWN PROBLEMS
592 =item literals in regex that are longer than 127 bytes
594 For native multibyte encodings (either fixed or variable length),
595 the current implementation of the regular expressions may introduce
596 recoding errors for regular expression literals longer than 127 bytes.
600 The encoding pragma is not supported on EBCDIC platforms.
601 (Porters who are willing and able to remove this limitation are
606 This pragma doesn't work well with format because PerlIO does not
607 get along very well with it. When format contains non-ascii
608 characters it prints funny or gets "wide character warnings".
609 To understand it, try the code below.
611 # Save this one in utf8
612 # replace *non-ascii* with a non-ascii string
618 $camel = "*non-ascii*";
619 binmode(STDOUT=>':encoding(utf8)'); # bang!
621 print $camel, "\n"; # fine
623 Without binmode this happens to work but without binmode, print()
624 fails instead of write().
626 At any rate, the very use of format is questionable when it comes to
627 unicode characters since you have to consider such things as character
628 width (i.e. double-width for ideographs) and directions (i.e. BIDI for
633 C<use encoding ...> is not thread-safe (i.e., do not use in threaded
638 =head2 The Logic of :locale
640 The logic of C<:locale> is as follows:
646 If the platform supports the langinfo(CODESET) interface, the codeset
647 returned is used as the default encoding for the open pragma.
651 If 1. didn't work but we are under the locale pragma, the environment
652 variables LC_ALL and LANG (in that order) are matched for encodings
653 (the part after C<.>, if any), and if any found, that is used
654 as the default encoding for the open pragma.
658 If 1. and 2. didn't work, the environment variables LC_ALL and LANG
659 (in that order) are matched for anything looking like UTF-8, and if
660 any found, C<:utf8> is used as the default encoding for the open
665 If your locale environment variables (LC_ALL, LC_CTYPE, LANG)
666 contain the strings 'UTF-8' or 'UTF8' (case-insensitive matching),
667 the default encoding of your STDIN, STDOUT, and STDERR, and of
668 B<any subsequent file open>, is UTF-8.
672 This pragma first appeared in Perl 5.8.0. For features that require
673 5.8.1 and better, see above.
675 The C<:locale> subpragma was implemented in 2.01, or Perl 5.8.6.
679 L<perlunicode>, L<Encode>, L<open>, L<Filter::Util::Call>,
681 Ch. 15 of C<Programming Perl (3rd Edition)>
682 by Larry Wall, Tom Christiansen, Jon Orwant;
683 O'Reilly & Associates; ISBN 0-596-00027-8