d5b32c7b5b6ebe3fc7ca7fff657e395d7e6f47fd
[p5sagit/p5-mst-13.2.git] / ext / Encode / encoding.pm
1 package encoding;
2 our $VERSION = do { my @r = (q$Revision: 1.26 $ =~ /\d+/g); sprintf "%d."."%02d" x $#r, @r };
3
4 use Encode;
5 use strict;
6
7 BEGIN {
8     if (ord("A") == 193) {
9         require Carp;
10         Carp::croak "encoding pragma does not support EBCDIC platforms";
11     }
12 }
13
14 sub import {
15     my $class = shift;
16     my $name  = shift;
17     my %arg = @_;
18     $name ||= $ENV{PERL_ENCODING};
19
20     my $enc = find_encoding($name);
21     unless (defined $enc) {
22         require Carp;
23         Carp::croak "Unknown encoding '$name'";
24     }
25     unless ($arg{Filter}){
26         ${^ENCODING} = $enc; # this is all you need, actually.
27         for my $h (qw(STDIN STDOUT)){
28             if ($arg{$h}){
29                 unless (defined find_encoding($arg{h})) {
30                     require Carp;
31                     Carp::croak "Unknown encoding for $h, '$arg{$h}'";
32                 }
33                 eval qq{ binmode($h, ":encoding($arg{$h})") };
34             }else{
35                 unless (exists $arg{$h}){
36                     eval qq{ binmode($h, ":encoding($name)") };
37                 }
38             }
39             if ($@){
40                 require Carp;
41                 Carp::croak($@);
42             }
43         }
44     }else{
45         defined(${^ENCODING}) and undef ${^ENCODING};
46         eval {
47             require Filter::Util::Call ;
48             Filter::Util::Call->import ;
49             binmode(STDIN,  ":raw");
50             binmode(STDOUT, ":raw");
51             filter_add(sub{
52                            my $status;
53                            if (($status = filter_read()) > 0){
54                                $_ = $enc->decode($_, 1);
55                                # warn $_;
56                            }
57                            $status ;
58                        });
59         };
60         # warn "Filter installed";
61     }
62     return 1; # I doubt if we need it, though
63 }
64
65 sub unimport{
66     no warnings;
67     undef ${^ENCODING};
68     binmode(STDIN,  ":raw");
69     binmode(STDOUT, ":raw");
70     if ($INC{"Filter/Util/Call.pm"}){
71         eval { filter_del() };
72     }
73 }
74
75 1;
76 __END__
77 =pod
78
79 =head1 NAME
80
81 encoding -  allows you to write your script in non-asii or non-utf8
82
83 =head1 SYNOPSIS
84
85   use encoding "euc-jp"; # Jperl!
86
87   # or you can even do this if your shell supports euc-jp
88
89   > perl -Mencoding=euc-jp -e '...'
90
91   # or from the shebang line
92
93   #!/your/path/to/perl -Mencoding=euc-jp
94
95   # more control
96
97   # A simple euc-jp => utf-8 converter
98   use encoding "euc-jp", STDOUT => "utf8";  while(<>){print};
99
100   # "no encoding;" supported (but not scoped!)
101   no encoding;
102
103   # an alternate way, Filter
104   use encoding "euc-jp", Filter=>1;
105   use utf8;
106   # now you can use kanji identifiers -- in euc-jp!
107
108 =head1 ABSTRACT
109
110 Perl 5.6.0 has introduced Unicode support.  You could apply
111 C<substr()> and regexes even to complex CJK characters -- so long as
112 the script was written in UTF-8.  But back then text editors that
113 support UTF-8 was still rare and many users rather chose to writer
114 scripts in legacy encodings, given up whole new feature of Perl 5.6.
115
116 With B<encoding> pragma, you can write your script in any encoding you like
117 (so long as the C<Encode> module supports it) and still enjoy Unicode
118 support.  You can write a code in EUC-JP as follows;
119
120   my $Rakuda = "\xF1\xD1\xF1\xCC"; # Camel in Kanji
121                #<-char-><-char->   # 4 octets
122   s/\bCamel\b/$Rakuda/;
123
124 And with C<use encoding "euc-jp"> in effect, it is the same thing as
125 the code in UTF-8 as follow.
126
127   my $Rakuda = "\x{99F1}\x{99DD}"; # who Unicode Characters
128   s/\bCamel\b/$Rakuda/;
129
130 The B<encoding> pragma also modifies the file handle disciplines of
131 STDIN, STDOUT, and STDERR to the specified encoding.  Therefore,
132
133   use encoding "euc-jp";
134   my $message = "Camel is the symbol of perl.\n";
135   my $Rakuda = "\xF1\xD1\xF1\xCC"; # Camel in Kanji
136   $message =~ s/\bCamel\b/$Rakuda/;
137   print $message;
138
139 Will print "\xF1\xD1\xF1\xCC is the symbol of perl.\n", not
140 "\x{99F1}\x{99DD} is the symbol of perl.\n".
141
142 You can override this by giving extra arguments.  See below.
143
144 =head1 USAGE
145
146 =over 4
147
148 =item use encoding [I<ENCNAME>] ;
149
150 Sets the script encoding to I<ENCNAME> and file handle disciplines of
151 STDIN, STDOUT are set to ":encoding(I<ENCNAME>)". Note STDERR will not 
152 be changed.
153
154 If no encoding is specified, the environment variable L<PERL_ENCODING>
155 is consulted. If no  encoding can be found, C<Unknown encoding 'I<ENCNAME>'>
156 error will be thrown. 
157
158 Note that non-STD file handles remain unaffected.  Use C<use open> or
159 C<binmode> to change disciplines of those.
160
161 =item use encoding I<ENCNAME> [ STDIN =E<gt> I<ENCNAME_IN> ...] ;
162
163 You can also individually set encodings of STDIN and STDOUT via
164 STDI<FH> =E<gt> I<ENCNAME_FH> form.  In this case, you cannot omit the
165 first I<ENCNAME>.  C<STDI<FH> =E<gt> undef> turns IO transcoding
166 completely off.
167
168 =item no encoding;
169
170 Unsets the script encoding and the disciplines of STDIN, STDOUT are
171 reset to ":raw".
172
173 =back
174
175 =head1 CAVEATS
176
177 =head2 NOT SCOPED
178
179 The pragma is a per script, not a per block lexical.  Only the last
180 C<use encoding> or C<matters, and it affects B<the whole script>.
181 Though <no encoding> pragma is supported and C<use encoding> can
182 appear as many times as you want in a given script, the multiple use
183 of this pragma is discouraged.
184
185 =head2 DO NOT MIX MULTIPLE ENCODINGS
186
187 Notice that only literals (string or regular expression) having only
188 legacy code points are affected: if you mix data like this
189
190         \xDF\x{100}
191
192 the data is assumed to be in (Latin 1 and) Unicode, not in your native
193 encoding.  In other words, this will match in "greek":
194
195         "\xDF" =~ /\x{3af}/
196
197 but this will not
198
199         "\xDF\x{100}" =~ /\x{3af}\x{100}/
200
201 since the C<\xDF> on the left will B<not> be upgraded to C<\x{3af}>
202 because of the C<\x{100}> on the left.  You should not be mixing your
203 legacy data and Unicode in the same string.
204
205 This pragma also affects encoding of the 0x80..0xFF code point range:
206 normally characters in that range are left as eight-bit bytes (unless
207 they are combined with characters with code points 0x100 or larger,
208 in which case all characters need to become UTF-8 encoded), but if
209 the C<encoding> pragma is present, even the 0x80..0xFF range always
210 gets UTF-8 encoded.
211
212 After all, the best thing about this pragma is that you don't have to
213 resort to \x... just to spell your name in native encoding.  So feel
214 free to put your strings in your encoding in quotes and regexes.
215
216 =head1 NON-ASCII Identifiers and Filter option
217
218 The magic of C<use encoding> is not applied to the names of identifiers.
219 In order to make C<${"4eba"}++> ($man++, where man is a single ideograph)
220 work, you still need to write your script in UTF-8 or use a source filter.
221
222 In other words, the same restriction as Jperl applies.
223
224 If you dare experiment, however, you can try Fitlter option.
225
226 =over 4
227
228 =item use encoding I<ENCNAME> Filter=E<gt>1;
229
230 This turns encoding pragma into source filter.  While the default
231 approach just decodes interpolated literals (in qq() and qr()), this
232 will apply source filter to entire source code.  In this case, STDIN
233 and STDOUT remain untouched.
234
235 =back
236
237 What does this mean?  Your source code behaves as if it is written 
238 in UTF-8.  So even if your editor only supports Shift_JIS, for 
239 example.  You can still try examples in Chapter 15 of 
240 C<Programming Perl, 3rd Ed.>  For instance, you can use UTF-8
241 identifiers.
242
243 This option is significantly slower and (as of this writing) non-ASCII
244 identifiers are not very stable WITHOUT this option and with the
245 source code written in UTF-8.
246
247 To make your script in legacy encoding work with minimum effort, do
248 not use Filter=E<gt>1
249
250
251 =head1 EXAMPLE - Greekperl
252
253     use encoding "iso 8859-7";
254
255     # The \xDF of ISO 8859-7 (Greek) is \x{3af} in Unicode.
256
257     $a = "\xDF";
258     $b = "\x{100}";
259
260     printf "%#x\n", ord($a); # will print 0x3af, not 0xdf
261
262     $c = $a . $b;
263
264     # $c will be "\x{3af}\x{100}", not "\x{df}\x{100}".
265
266     # chr() is affected, and ...
267
268     print "mega\n"  if ord(chr(0xdf)) == 0x3af;
269
270     # ... ord() is affected by the encoding pragma ...
271
272     print "tera\n" if ord(pack("C", 0xdf)) == 0x3af;
273
274     # ... as are eq and cmp ...
275
276     print "peta\n" if "\x{3af}" eq  pack("C", 0xdf);
277     print "exa\n"  if "\x{3af}" cmp pack("C", 0xdf) == 0;
278
279     # ... but pack/unpack C are not affected, in case you still
280     # want back to your native encoding
281
282     print "zetta\n" if unpack("C", (pack("C", 0xdf))) == 0xdf;
283
284 =head1 KNOWN PROBLEMS
285
286 For native multibyte encodings (either fixed or variable length)
287 the current implementation of the regular expressions may introduce
288 recoding errors for longer regular expression literals than 127 bytes.
289
290 The encoding pragma is not supported on EBCDIC platforms.
291 (Porters wanted.)
292
293 =head1 SEE ALSO
294
295 L<perlunicode>, L<Encode>, L<open>, L<Filter::Util::Call>,
296
297 Ch. 15 of C<Programming Perl (3rd Edition)>
298 by Larry Wall, Tom Christiansen, Jon Orwant;
299 O'Reilly & Associates; ISBN 0-596-00027-8
300
301 =cut