1encoding(3)           User Contributed Perl Documentation          encoding(3)
2
3
4

NAME

6       encoding - allows you to write your script in non-ASCII and non-UTF-8
7

WARNING

9       This module has been deprecated since perl v5.18.  See "DESCRIPTION"
10       and "BUGS".
11

SYNOPSIS

13         use encoding "greek";  # Perl like Greek to you?
14         use encoding "euc-jp"; # Jperl!
15
16         # or you can even do this if your shell supports your native encoding
17
18         perl -Mencoding=latin2 -e'...' # Feeling centrally European?
19         perl -Mencoding=euc-kr -e'...' # Or Korean?
20
21         # more control
22
23         # A simple euc-cn => utf-8 converter
24         use encoding "euc-cn", STDOUT => "utf8";  while(<>){print};
25
26         # "no encoding;" supported
27         no encoding;
28
29         # an alternate way, Filter
30         use encoding "euc-jp", Filter=>1;
31         # now you can use kanji identifiers -- in euc-jp!
32
33         # encode based on the current locale - specialized purposes only;
34         # fraught with danger!!
35         use encoding ':locale';
36

DESCRIPTION

38       This pragma is used to enable a Perl script to be written in encodings
39       that aren't strictly ASCII nor UTF-8.  It translates all or portions of
40       the Perl program script from a given encoding into UTF-8, and changes
41       the PerlIO layers of "STDIN" and "STDOUT" to the encoding specified.
42
43       This pragma dates from the days when UTF-8-enabled editors were
44       uncommon.  But that was long ago, and the need for it is greatly
45       diminished.  That, coupled with the fact that it doesn't work with
46       threads, along with other problems, (see "BUGS") have led to its being
47       deprecated.  It is planned to remove this pragma in a future Perl
48       version.  New code should be written in UTF-8, and the "use utf8"
49       pragma used instead (see perluniintro and utf8 for details).  Old code
50       should be converted to UTF-8, via something like the recipe in the
51       "SYNOPSIS" (though this simple approach may require manual adjustments
52       afterwards).
53
54       If UTF-8 is not an option, it is recommended that one use a simple
55       source filter, such as that provided by Filter::Encoding on CPAN or
56       this pragma's own "Filter" option (see below).
57
58       The only legitimate use of this pragma is almost certainly just one per
59       file, near the top, with file scope, as the file is likely going to
60       only be written in one encoding.  Further restrictions apply in Perls
61       before v5.22 (see "Prior to Perl v5.22").
62
63       There are two basic modes of operation (plus turning if off):
64
65       "use encoding ['ENCNAME'] ;"
66           Please note: This mode of operation is no longer supported as of
67           Perl v5.26.
68
69           This is the normal operation.  It translates various literals
70           encountered in the Perl source file from the encoding ENCNAME into
71           UTF-8, and similarly converts character code points.  This is used
72           when the script is a combination of ASCII (for the variable names
73           and punctuation, etc), but the literal data is in the specified
74           encoding.
75
76           ENCNAME is optional.  If omitted, the encoding specified in the
77           environment variable "PERL_ENCODING" is used.  If this isn't set,
78           or the resolved-to encoding is not known to "Encode", the error
79           "Unknown encoding 'ENCNAME'" will be thrown.
80
81           Starting in Perl v5.8.6 ("Encode" version 2.0.1), ENCNAME may be
82           the name ":locale".  This is for very specialized applications, and
83           is documented in "The ":locale" sub-pragma" below.
84
85           The literals that are converted are "q//, qq//, qr//, qw///, qx//",
86           and starting in v5.8.1, "tr///".  Operations that do conversions
87           include "chr", "ord", "utf8::upgrade" (but not "utf8::downgrade"),
88           and "chomp".
89
90           Also starting in v5.8.1, the "DATA" pseudo-filehandle is translated
91           from the encoding into UTF-8.
92
93           For example, you can write code in EUC-JP as follows:
94
95             my $Rakuda = "\xF1\xD1\xF1\xCC"; # Camel in Kanji
96                          #<-char-><-char->   # 4 octets
97             s/\bCamel\b/$Rakuda/;
98
99           And with "use encoding "euc-jp"" in effect, it is the same thing as
100           that code in UTF-8:
101
102             my $Rakuda = "\x{99F1}\x{99DD}"; # two Unicode Characters
103             s/\bCamel\b/$Rakuda/;
104
105           See "EXAMPLE" below for a more complete example.
106
107           Unless "${^UNICODE}" (available starting in v5.8.2) exists and is
108           non-zero, the PerlIO layers of "STDIN" and "STDOUT" are set to
109           ":encoding(ENCNAME)".  Therefore,
110
111             use encoding "euc-jp";
112             my $message = "Camel is the symbol of perl.\n";
113             my $Rakuda = "\xF1\xD1\xF1\xCC"; # Camel in Kanji
114             $message =~ s/\bCamel\b/$Rakuda/;
115             print $message;
116
117           will print
118
119            "\xF1\xD1\xF1\xCC is the symbol of perl.\n"
120
121           not
122
123            "\x{99F1}\x{99DD} is the symbol of perl.\n"
124
125           You can override this by giving extra arguments; see below.
126
127           Note that "STDERR" WILL NOT be changed, regardless.
128
129           Also note that non-STD file handles remain unaffected.  Use "use
130           open" or "binmode" to change the layers of those.
131
132       "use encoding ENCNAME, Filter=>1;"
133           This operates as above, but the "Filter" argument with a non-zero
134           value causes the entire script, and not just literals, to be
135           translated from the encoding into UTF-8.  This allows identifiers
136           in the source to be in that encoding as well.  (Problems may occur
137           if the encoding is not a superset of ASCII; imagine all your semi-
138           colons being translated into something different.)  One can use
139           this form to make
140
141            ${"\x{4eba}"}++
142
143           work.  (This is equivalent to "$human++", where human is a single
144           Han ideograph).
145
146           This effectively means that your source code behaves as if it were
147           written in UTF-8 with "'use utf8"' in effect.  So even if your
148           editor only supports Shift_JIS, for example, you can still try
149           examples in Chapter 15 of "Programming Perl, 3rd Ed.".
150
151           This option is significantly slower than the other one.
152
153       "no encoding;"
154           Unsets the script encoding. The layers of "STDIN", "STDOUT" are
155           reset to "":raw"" (the default unprocessed raw stream of bytes).
156

OPTIONS

158   Setting "STDIN" and/or "STDOUT" individually
159       The encodings of "STDIN" and "STDOUT" are individually settable by
160       parameters to the pragma:
161
162        use encoding 'euc-tw', STDIN => 'greek'  ...;
163
164       In this case, you cannot omit the first ENCNAME.  "STDIN => undef"
165       turns the I/O transcoding completely off for that filehandle.
166
167       When "${^UNICODE}" (available starting in v5.8.2) exists and is non-
168       zero, these options will be completely ignored.  See ""${^UNICODE}"" in
169       perlvar and ""-C"" in perlrun for details.
170
171   The ":locale" sub-pragma
172       Starting in v5.8.6, the encoding name may be ":locale".  This means
173       that the encoding is taken from the current locale, and not hard-coded
174       by the pragma.  Since a script really can only be encoded in exactly
175       one encoding, this option is dangerous.  It makes sense only if the
176       script itself is written in ASCII, and all the possible locales that
177       will be in use when the script is executed are supersets of ASCII.
178       That means that the script itself doesn't get changed, but the I/O
179       handles have the specified encoding added, and the operations like
180       "chr" and "ord" use that encoding.
181
182       The logic of finding which locale ":locale" uses is as follows:
183
184       1.  If the platform supports the langinfo(CODESET) interface, the
185           codeset returned is used as the default encoding for the open
186           pragma.
187
188       2.  If 1. didn't work but we are under the locale pragma, the
189           environment variables "LC_ALL" and "LANG" (in that order) are
190           matched for encodings (the part after ""."", if any), and if any
191           found, that is used as the default encoding for the open pragma.
192
193       3.  If 1. and 2. didn't work, the environment variables "LC_ALL" and
194           "LANG" (in that order) are matched for anything looking like UTF-8,
195           and if any found, ":utf8" is used as the default encoding for the
196           open pragma.
197
198       If your locale environment variables ("LC_ALL", "LC_CTYPE", "LANG")
199       contain the strings 'UTF-8' or 'UTF8' (case-insensitive matching), the
200       default encoding of your "STDIN", "STDOUT", and "STDERR", and of any
201       subsequent file open, is UTF-8.
202

CAVEATS

204   SIDE EFFECTS
205       •   If the "encoding" pragma is in scope then the lengths returned are
206           calculated from the length of $/ in Unicode characters, which is
207           not always the same as the length of $/ in the native encoding.
208
209       •   Without this pragma, if strings operating under byte semantics and
210           strings with Unicode character data are concatenated, the new
211           string will be created by decoding the byte strings as ISO 8859-1
212           (Latin-1).
213
214           The encoding pragma changes this to use the specified encoding
215           instead.  For example:
216
217               use encoding 'utf8';
218               my $string = chr(20000); # a Unicode string
219               utf8::encode($string);   # now it's a UTF-8 encoded byte string
220               # concatenate with another Unicode string
221               print length($string . chr(20000));
222
223           Will print 2, because $string is upgraded as UTF-8.  Without "use
224           encoding 'utf8';", it will print 4 instead, since $string is three
225           octets when interpreted as Latin-1.
226
227   DO NOT MIX MULTIPLE ENCODINGS
228       Notice that only literals (string or regular expression) having only
229       legacy code points are affected: if you mix data like this
230
231           \x{100}\xDF
232           \xDF\x{100}
233
234       the data is assumed to be in (Latin 1 and) Unicode, not in your native
235       encoding.  In other words, this will match in "greek":
236
237           "\xDF" =~ /\x{3af}/
238
239       but this will not
240
241           "\xDF\x{100}" =~ /\x{3af}\x{100}/
242
243       since the "\xDF" (ISO 8859-7 GREEK SMALL LETTER IOTA WITH TONOS) on the
244       left will not be upgraded to "\x{3af}" (Unicode GREEK SMALL LETTER IOTA
245       WITH TONOS) because of the "\x{100}" on the left.  You should not be
246       mixing your legacy data and Unicode in the same string.
247
248       This pragma also affects encoding of the 0x80..0xFF code point range:
249       normally characters in that range are left as eight-bit bytes (unless
250       they are combined with characters with code points 0x100 or larger, in
251       which case all characters need to become UTF-8 encoded), but if the
252       "encoding" pragma is present, even the 0x80..0xFF range always gets
253       UTF-8 encoded.
254
255       After all, the best thing about this pragma is that you don't have to
256       resort to \x{....} just to spell your name in a native encoding.  So
257       feel free to put your strings in your encoding in quotes and regexes.
258
259   Prior to Perl v5.22
260       The pragma was a per script, not a per block lexical.  Only the last
261       "use encoding" or "no encoding" mattered, and it affected the whole
262       script.  However, the "no encoding" pragma was supported and "use
263       encoding" could appear as many times as you want in a given script
264       (though only the last was effective).
265
266       Since the scope wasn't lexical, other modules' use of "chr", "ord",
267       etc.  were affected.  This leads to spooky, incorrect action at a
268       distance that is hard to debug.
269
270       This means you would have to be very careful of the load order:
271
272         # called module
273         package Module_IN_BAR;
274         use encoding "bar";
275         # stuff in "bar" encoding here
276         1;
277
278         # caller script
279         use encoding "foo"
280         use Module_IN_BAR;
281         # surprise! use encoding "bar" is in effect.
282
283       The best way to avoid this oddity is to use this pragma RIGHT AFTER
284       other modules are loaded.  i.e.
285
286         use Module_IN_BAR;
287         use encoding "foo";
288
289   Prior to Encode version 1.87
290       •   "STDIN" and "STDOUT" were not set under the filter option.  And
291           "STDIN=>ENCODING" and "STDOUT=>ENCODING" didn't work like non-
292           filter version.
293
294       •   "use utf8" wasn't implicitly declared so you have to "use utf8" to
295           do
296
297            ${"\x{4eba}"}++
298
299   Prior to Perl v5.8.1
300       "NON-EUC" doublebyte encodings
301           Because perl needs to parse the script before applying this pragma,
302           such encodings as Shift_JIS and Big-5 that may contain '\'
303           (BACKSLASH; "\x5c") in the second byte fail because the second byte
304           may accidentally escape the quoting character that follows.
305
306       "tr///"
307           The encoding pragma works by decoding string literals in
308           "q//,qq//,qr//,qw///, qx//" and so forth.  In perl v5.8.0, this
309           does not apply to "tr///".  Therefore,
310
311             use encoding 'euc-jp';
312             #....
313             $kana =~ tr/\xA4\xA1-\xA4\xF3/\xA5\xA1-\xA5\xF3/;
314             #           -------- -------- -------- --------
315
316           Does not work as
317
318             $kana =~ tr/\x{3041}-\x{3093}/\x{30a1}-\x{30f3}/;
319
320           Legend of characters above
321                 utf8     euc-jp   charnames::viacode()
322                 -----------------------------------------
323                 \x{3041} \xA4\xA1 HIRAGANA LETTER SMALL A
324                 \x{3093} \xA4\xF3 HIRAGANA LETTER N
325                 \x{30a1} \xA5\xA1 KATAKANA LETTER SMALL A
326                 \x{30f3} \xA5\xF3 KATAKANA LETTER N
327
328           This counterintuitive behavior has been fixed in perl v5.8.1.
329
330           In perl v5.8.0, you can work around this as follows;
331
332             use encoding 'euc-jp';
333             #  ....
334             eval qq{ \$kana =~ tr/\xA4\xA1-\xA4\xF3/\xA5\xA1-\xA5\xF3/ };
335
336           Note the "tr//" expression is surrounded by "qq{}".  The idea
337           behind this is the same as the classic idiom that makes "tr///"
338           'interpolate':
339
340              tr/$from/$to/;            # wrong!
341              eval qq{ tr/$from/$to/ }; # workaround.
342

EXAMPLE - Greekperl

344           use encoding "iso 8859-7";
345
346           # \xDF in ISO 8859-7 (Greek) is \x{3af} in Unicode.
347
348           $a = "\xDF";
349           $b = "\x{100}";
350
351           printf "%#x\n", ord($a); # will print 0x3af, not 0xdf
352
353           $c = $a . $b;
354
355           # $c will be "\x{3af}\x{100}", not "\x{df}\x{100}".
356
357           # chr() is affected, and ...
358
359           print "mega\n"  if ord(chr(0xdf)) == 0x3af;
360
361           # ... ord() is affected by the encoding pragma ...
362
363           print "tera\n" if ord(pack("C", 0xdf)) == 0x3af;
364
365           # ... as are eq and cmp ...
366
367           print "peta\n" if "\x{3af}" eq  pack("C", 0xdf);
368           print "exa\n"  if "\x{3af}" cmp pack("C", 0xdf) == 0;
369
370           # ... but pack/unpack C are not affected, in case you still
371           # want to go back to your native encoding
372
373           print "zetta\n" if unpack("C", (pack("C", 0xdf))) == 0xdf;
374

BUGS

376       Thread safety
377           "use encoding ..." is not thread-safe (i.e., do not use in threaded
378           applications).
379
380       Can't be used by more than one module in a single program.
381           Only one encoding is allowed.  If you combine modules in a program
382           that have different encodings, only one will be actually used.
383
384       Other modules using "STDIN" and "STDOUT" get the encoded stream
385           They may be expecting something completely different.
386
387       literals in regex that are longer than 127 bytes
388           For native multibyte encodings (either fixed or variable length),
389           the current implementation of the regular expressions may introduce
390           recoding errors for regular expression literals longer than 127
391           bytes.
392
393       EBCDIC
394           The encoding pragma is not supported on EBCDIC platforms.
395
396       "format"
397           This pragma doesn't work well with "format" because PerlIO does not
398           get along very well with it.  When "format" contains non-ASCII
399           characters it prints funny or gets "wide character warnings".  To
400           understand it, try the code below.
401
402             # Save this one in utf8
403             # replace *non-ascii* with a non-ascii string
404             my $camel;
405             format STDOUT =
406             *non-ascii*@>>>>>>>
407             $camel
408             .
409             $camel = "*non-ascii*";
410             binmode(STDOUT=>':encoding(utf8)'); # bang!
411             write;              # funny
412             print $camel, "\n"; # fine
413
414           Without binmode this happens to work but without binmode, print()
415           fails instead of write().
416
417           At any rate, the very use of "format" is questionable when it comes
418           to unicode characters since you have to consider such things as
419           character width (i.e. double-width for ideographs) and directions
420           (i.e. BIDI for Arabic and Hebrew).
421
422       See also "CAVEATS"
423

HISTORY

425       This pragma first appeared in Perl v5.8.0.  It has been enhanced in
426       later releases as specified above.
427

SEE ALSO

429       perlunicode, Encode, open, Filter::Util::Call,
430
431       Ch. 15 of "Programming Perl (3rd Edition)" by Larry Wall, Tom
432       Christiansen, Jon Orwant; O'Reilly & Associates; ISBN 0-596-00027-8
433
434
435
436perl v5.38.0                      2023-07-20                       encoding(3)
Impressum