📄 encoding.pm
字号:
Because perl needs to parse script before applying this pragma, suchencodings as Shift_JIS and Big-5 that may contain '\' (BACKSLASH;\x5c) in the second byte fails because the second byte mayaccidentally escape the quoting character that follows. Perl 5.8.1or later fixes this problem.=item tr// C<tr//> was overlooked by Perl 5 porters when they released perl 5.8.0See the section below for details.=item DATA pseudo-filehandleAnother feature that was overlooked was C<DATA>. =back=head1 USAGE=over 4=item use encoding [I<ENCNAME>] ;Sets the script encoding to I<ENCNAME>. And unless ${^UNICODE} exists and non-zero, PerlIO layers of STDIN and STDOUT are set to":encoding(I<ENCNAME>)".Note that STDERR WILL NOT be changed.Also note that non-STD file handles remain unaffected. Use C<useopen> or C<binmode> to change layers of those.If no encoding is specified, the environment variable L<PERL_ENCODING>is consulted. If no encoding can be found, the error C<Unknown encoding'I<ENCNAME>'> will be thrown.=item use encoding I<ENCNAME> [ STDIN =E<gt> I<ENCNAME_IN> ...] ;You can also individually set encodings of STDIN and STDOUT via theC<< STDIN => I<ENCNAME> >> form. In this case, you cannot omit thefirst I<ENCNAME>. C<< STDIN => undef >> turns the IO transcodingcompletely off.When ${^UNICODE} exists and non-zero, these options will completelyignored. ${^UNICODE} is a variable introduced in perl 5.8.1. SeeL<perlrun> see L<perlvar/"${^UNICODE}"> and L<perlrun/"-C"> fordetails (perl 5.8.1 and later).=item use encoding I<ENCNAME> Filter=E<gt>1;This turns the encoding pragma into a source filter. While thedefault approach just decodes interpolated literals (in qq() andqr()), this will apply a source filter to the entire source code. SeeL</"The Filter Option"> below for details.=item no encoding;Unsets the script encoding. The layers of STDIN, STDOUT arereset to ":raw" (the default unprocessed raw stream of bytes).=back=head1 The Filter OptionThe magic of C<use encoding> is not applied to the names ofidentifiers. In order to make C<${"\x{4eba}"}++> ($human++, where humanis a single Han ideograph) work, you still need to write your scriptin UTF-8 -- or use a source filter. That's what 'Filter=>1' does.What does this mean? Your source code behaves as if it is written inUTF-8 with 'use utf8' in effect. So even if your editor only supportsShift_JIS, for example, you can still try examples in Chapter 15 ofC<Programming Perl, 3rd Ed.>. For instance, you can use UTF-8identifiers.This option is significantly slower and (as of this writing) non-ASCIIidentifiers are not very stable WITHOUT this option and with thesource code written in UTF-8.=head2 Filter-related changes at Encode version 1.87=over=item *The Filter option now sets STDIN and STDOUT like non-filter options.And C<< STDIN=>I<ENCODING> >> and C<< STDOUT=>I<ENCODING> >> work likenon-filter version.=item *C<use utf8> is implicitly declared so you no longer have to C<useutf8> to C<${"\x{4eba}"}++>.=back=head1 CAVEATS=head2 NOT SCOPEDThe pragma is a per script, not a per block lexical. Only the lastC<use encoding> or C<no encoding> matters, and it affects B<the whole script>. However, the <no encoding> pragma is supported and B<use encoding> can appear as many times as you want in a given script. The multiple use of this pragma is discouraged.By the same reason, the use this pragma inside modules is alsodiscouraged (though not as strongly discouraged as the case above. See below).If you still have to write a module with this pragma, be very carefulof the load order. See the codes below; # called module package Module_IN_BAR; use encoding "bar"; # stuff in "bar" encoding here 1; # caller script use encoding "foo" use Module_IN_BAR; # surprise! use encoding "bar" is in effect.The best way to avoid this oddity is to use this pragma RIGHT AFTERother modules are loaded. i.e. use Module_IN_BAR; use encoding "foo";=head2 DO NOT MIX MULTIPLE ENCODINGSNotice that only literals (string or regular expression) having onlylegacy code points are affected: if you mix data like this \xDF\x{100}the data is assumed to be in (Latin 1 and) Unicode, not in your nativeencoding. In other words, this will match in "greek": "\xDF" =~ /\x{3af}/but this will not "\xDF\x{100}" =~ /\x{3af}\x{100}/since the C<\xDF> (ISO 8859-7 GREEK SMALL LETTER IOTA WITH TONOS) onthe left will B<not> be upgraded to C<\x{3af}> (Unicode GREEK SMALLLETTER IOTA WITH TONOS) because of the C<\x{100}> on the left. Youshould not be mixing your legacy data and Unicode in the same string.This pragma also affects encoding of the 0x80..0xFF code point range:normally characters in that range are left as eight-bit bytes (unlessthey are combined with characters with code points 0x100 or larger,in which case all characters need to become UTF-8 encoded), but ifthe C<encoding> pragma is present, even the 0x80..0xFF range alwaysgets UTF-8 encoded.After all, the best thing about this pragma is that you don't have toresort to \x{....} just to spell your name in a native encoding.So feel free to put your strings in your encoding in quotes andregexes.=head2 tr/// with rangesThe B<encoding> pragma works by decoding string literals inC<q//,qq//,qr//,qw///, qx//> and so forth. In perl 5.8.0, thisdoes not apply to C<tr///>. Therefore, use encoding 'euc-jp'; #.... $kana =~ tr/\xA4\xA1-\xA4\xF3/\xA5\xA1-\xA5\xF3/; # -------- -------- -------- --------Does not work as $kana =~ tr/\x{3041}-\x{3093}/\x{30a1}-\x{30f3}/;=over=item Legend of characters above utf8 euc-jp charnames::viacode() ----------------------------------------- \x{3041} \xA4\xA1 HIRAGANA LETTER SMALL A \x{3093} \xA4\xF3 HIRAGANA LETTER N \x{30a1} \xA5\xA1 KATAKANA LETTER SMALL A \x{30f3} \xA5\xF3 KATAKANA LETTER N=backThis counterintuitive behavior has been fixed in perl 5.8.1.=head3 workaround to tr///;In perl 5.8.0, you can work around as follows; use encoding 'euc-jp'; # .... eval qq{ \$kana =~ tr/\xA4\xA1-\xA4\xF3/\xA5\xA1-\xA5\xF3/ };Note the C<tr//> expression is surrounded by C<qq{}>. The idea behindis the same as classic idiom that makes C<tr///> 'interpolate'. tr/$from/$to/; # wrong! eval qq{ tr/$from/$to/ }; # workaround.Nevertheless, in case of B<encoding> pragma even C<q//> is affected soC<tr///> not being decoded was obviously against the will of Perl5Porters so it has been fixed in Perl 5.8.1 or later.=head1 EXAMPLE - Greekperl use encoding "iso 8859-7"; # \xDF in ISO 8859-7 (Greek) is \x{3af} in Unicode. $a = "\xDF"; $b = "\x{100}"; printf "%#x\n", ord($a); # will print 0x3af, not 0xdf $c = $a . $b; # $c will be "\x{3af}\x{100}", not "\x{df}\x{100}". # chr() is affected, and ... print "mega\n" if ord(chr(0xdf)) == 0x3af; # ... ord() is affected by the encoding pragma ... print "tera\n" if ord(pack("C", 0xdf)) == 0x3af; # ... as are eq and cmp ... print "peta\n" if "\x{3af}" eq pack("C", 0xdf); print "exa\n" if "\x{3af}" cmp pack("C", 0xdf) == 0; # ... but pack/unpack C are not affected, in case you still # want to go back to your native encoding print "zetta\n" if unpack("C", (pack("C", 0xdf))) == 0xdf;=head1 KNOWN PROBLEMS=over=item literals in regex that are longer than 127 bytesFor native multibyte encodings (either fixed or variable length),the current implementation of the regular expressions may introducerecoding errors for regular expression literals longer than 127 bytes.=item EBCDICThe encoding pragma is not supported on EBCDIC platforms.(Porters who are willing and able to remove this limitation arewelcome.)=item formatThis pragma doesn't work well with format because PerlIO does notget along very well with it. When format contains non-asciicharacters it prints funny or gets "wide character warnings".To understand it, try the code below. # Save this one in utf8 # replace *non-ascii* with a non-ascii string my $camel; format STDOUT = *non-ascii*@>>>>>>> $camel . $camel = "*non-ascii*"; binmode(STDOUT=>':encoding(utf8)'); # bang! write; # funny print $camel, "\n"; # fineWithout binmode this happens to work but without binmode, print()fails instead of write().At any rate, the very use of format is questionable when it comes tounicode characters since you have to consider such things as characterwidth (i.e. double-width for ideographs) and directions (i.e. BIDI forArabic and Hebrew).=item Thread safetyC<use encoding ...> is not thread-safe (i.e., do not use in threadedapplications).=back=head2 The Logic of :localeThe logic of C<:locale> is as follows:=over 4=item 1.If the platform supports the langinfo(CODESET) interface, the codesetreturned is used as the default encoding for the open pragma.=item 2.If 1. didn't work but we are under the locale pragma, the environmentvariables LC_ALL and LANG (in that order) are matched for encodings(the part after C<.>, if any), and if any found, that is used as the default encoding for the open pragma.=item 3.If 1. and 2. didn't work, the environment variables LC_ALL and LANG(in that order) are matched for anything looking like UTF-8, and ifany found, C<:utf8> is used as the default encoding for the openpragma.=backIf your locale environment variables (LC_ALL, LC_CTYPE, LANG)contain the strings 'UTF-8' or 'UTF8' (case-insensitive matching),the default encoding of your STDIN, STDOUT, and STDERR, and ofB<any subsequent file open>, is UTF-8.=head1 HISTORYThis pragma first appeared in Perl 5.8.0. For features that require 5.8.1 and better, see above.The C<:locale> subpragma was implemented in 2.01, or Perl 5.8.6.=head1 SEE ALSOL<perlunicode>, L<Encode>, L<open>, L<Filter::Util::Call>,Ch. 15 of C<Programming Perl (3rd Edition)>by Larry Wall, Tom Christiansen, Jon Orwant;O'Reilly & Associates; ISBN 0-596-00027-8=cut
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -