This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Remove my todo commits from perldelta template
[perl5.git] / pod / perllocale.pod
1 =head1 NAME
2
3 perllocale - Perl locale handling (internationalization and localization)
4
5 =head1 DESCRIPTION
6
7 Locales these days have been mostly been supplanted by Unicode, but Perl
8 continues to support them.  See L</Unicode and UTF-8> below.
9
10 Perl supports language-specific notions of data such as "is this
11 a letter", "what is the uppercase equivalent of this letter", and
12 "which of these letters comes first".  These are important issues,
13 especially for languages other than English--but also for English: it
14 would be naE<iuml>ve to imagine that C<A-Za-z> defines all the "letters"
15 needed to write correct English. Perl is also aware that some character other
16 than "." may be preferred as a decimal point, and that output date
17 representations may be language-specific.  The process of making an
18 application take account of its users' preferences in such matters is
19 called B<internationalization> (often abbreviated as B<i18n>); telling
20 such an application about a particular set of preferences is known as
21 B<localization> (B<l10n>).
22
23 Perl can understand language-specific data via the standardized (ISO C,
24 XPG4, POSIX 1.c) method called "the locale system". The locale system is
25 controlled per application using one pragma, one function call, and
26 several environment variables.
27
28 B<NOTE>: This feature is new in Perl 5.004, and does not apply unless an
29 application specifically requests it--see L<Backward compatibility>.
30 The one exception is that write() now B<always> uses the current locale
31 - see L<"NOTES">.
32
33 =head1 PREPARING TO USE LOCALES
34
35 If Perl applications are to understand and present your data
36 correctly according a locale of your choice, B<all> of the following
37 must be true:
38
39 =over 4
40
41 =item *
42
43 B<Your operating system must support the locale system>.  If it does,
44 you should find that the setlocale() function is a documented part of
45 its C library.
46
47 =item *
48
49 B<Definitions for locales that you use must be installed>.  You, or
50 your system administrator, must make sure that this is the case. The
51 available locales, the location in which they are kept, and the manner
52 in which they are installed all vary from system to system.  Some systems
53 provide only a few, hard-wired locales and do not allow more to be
54 added.  Others allow you to add "canned" locales provided by the system
55 supplier.  Still others allow you or the system administrator to define
56 and add arbitrary locales.  (You may have to ask your supplier to
57 provide canned locales that are not delivered with your operating
58 system.)  Read your system documentation for further illumination.
59
60 =item *
61
62 B<Perl must believe that the locale system is supported>.  If it does,
63 C<perl -V:d_setlocale> will say that the value for C<d_setlocale> is
64 C<define>.
65
66 =back
67
68 If you want a Perl application to process and present your data
69 according to a particular locale, the application code should include
70 the S<C<use locale>> pragma (see L<The use locale pragma>) where
71 appropriate, and B<at least one> of the following must be true:
72
73 =over 4
74
75 =item 1
76
77 B<The locale-determining environment variables (see L<"ENVIRONMENT">)
78 must be correctly set up> at the time the application is started, either
79 by yourself or by whoever set up your system account; or
80
81 =item 2
82
83 B<The application must set its own locale> using the method described in
84 L<The setlocale function>.
85
86 =back
87
88 =head1 USING LOCALES
89
90 =head2 The use locale pragma
91
92 By default, Perl ignores the current locale.  The S<C<use locale>>
93 pragma and the C</l> regular expression modifier tell Perl to use the
94 current locale for some operations (C</l> for just pattern matching).
95
96 The current locale is set at execution time by
97 L<setlocale()|/The setlocale function> described below.  If that function
98 hasn't yet been called in the course of the program's execution, the
99 current locale is that which was determined by the L<"ENVIRONMENT"> in
100 effect at the start of the program, except that
101 C<L<LC_NUMERIC|/Category LC_NUMERIC: Numeric Formatting>> is always
102 initialized to the C locale (mentioned under L<Finding locales>).
103 If there is no valid environment, the current locale is undefined.  It
104 is likely, but not necessarily, the "C" locale.
105
106 The operations that are affected by locale are:
107
108 =over 4
109
110 =item *
111
112 B<The comparison operators> (C<lt>, C<le>, C<cmp>, C<ge>, and C<gt>) and
113 the POSIX string collation functions strcoll() and strxfrm() use
114 C<LC_COLLATE>.  sort() is also affected if used without an
115 explicit comparison function, because it uses C<cmp> by default.
116
117 B<Note:> C<eq> and C<ne> are unaffected by locale: they always
118 perform a char-by-char comparison of their scalar operands.  What's
119 more, if C<cmp> finds that its operands are equal according to the
120 collation sequence specified by the current locale, it goes on to
121 perform a char-by-char comparison, and only returns I<0> (equal) if the
122 operands are char-for-char identical.  If you really want to know whether
123 two strings--which C<eq> and C<cmp> may consider different--are equal
124 as far as collation in the locale is concerned, see the discussion in
125 L<Category LC_COLLATE: Collation>.
126
127 =item *
128
129 B<Regular expressions and case-modification functions> (uc(), lc(),
130 ucfirst(), and lcfirst()) use C<LC_CTYPE>
131
132 =item *
133
134 B<Format declarations> (format()) use C<LC_NUMERIC>
135
136 =item *
137
138 B<The POSIX date formatting function> (strftime()) uses C<LC_TIME>.
139
140 =back
141
142 C<LC_COLLATE>, C<LC_CTYPE>, and so on, are discussed further in 
143 L<LOCALE CATEGORIES>.
144
145 The default behavior is restored with the S<C<no locale>> pragma, or
146 upon reaching the end of block enclosing C<use locale>.
147
148 The string result of any operation that uses locale
149 information is tainted, as it is possible for a locale to be
150 untrustworthy.  See L<"SECURITY">.
151
152 =head2 The setlocale function
153
154 You can switch locales as often as you wish at run time with the
155 POSIX::setlocale() function:
156
157         # This functionality not usable prior to Perl 5.004
158         require 5.004;
159
160         # Import locale-handling tool set from POSIX module.
161         # This example uses: setlocale -- the function call
162         #                    LC_CTYPE -- explained below
163         use POSIX qw(locale_h);
164
165         # query and save the old locale
166         $old_locale = setlocale(LC_CTYPE);
167
168         setlocale(LC_CTYPE, "fr_CA.ISO8859-1");
169         # LC_CTYPE now in locale "French, Canada, codeset ISO 8859-1"
170
171         setlocale(LC_CTYPE, "");
172         # LC_CTYPE now reset to default defined by LC_ALL/LC_CTYPE/LANG
173         # environment variables.  See below for documentation.
174
175         # restore the old locale
176         setlocale(LC_CTYPE, $old_locale);
177
178 The first argument of setlocale() gives the B<category>, the second the
179 B<locale>.  The category tells in what aspect of data processing you
180 want to apply locale-specific rules.  Category names are discussed in
181 L<LOCALE CATEGORIES> and L<"ENVIRONMENT">.  The locale is the name of a
182 collection of customization information corresponding to a particular
183 combination of language, country or territory, and codeset.  Read on for
184 hints on the naming of locales: not all systems name locales as in the
185 example.
186
187 If no second argument is provided and the category is something else
188 than LC_ALL, the function returns a string naming the current locale
189 for the category.  You can use this value as the second argument in a
190 subsequent call to setlocale().
191
192 If no second argument is provided and the category is LC_ALL, the
193 result is implementation-dependent.  It may be a string of
194 concatenated locale names (separator also implementation-dependent)
195 or a single locale name.  Please consult your setlocale(3) man page for
196 details.
197
198 If a second argument is given and it corresponds to a valid locale,
199 the locale for the category is set to that value, and the function
200 returns the now-current locale value.  You can then use this in yet
201 another call to setlocale().  (In some implementations, the return
202 value may sometimes differ from the value you gave as the second
203 argument--think of it as an alias for the value you gave.)
204
205 As the example shows, if the second argument is an empty string, the
206 category's locale is returned to the default specified by the
207 corresponding environment variables.  Generally, this results in a
208 return to the default that was in force when Perl started up: changes
209 to the environment made by the application after startup may or may not
210 be noticed, depending on your system's C library.
211
212 If the second argument does not correspond to a valid locale, the locale
213 for the category is not changed, and the function returns I<undef>.
214
215 For further information about the categories, consult setlocale(3).
216
217 =head2 Finding locales
218
219 For locales available in your system, consult also setlocale(3) to
220 see whether it leads to the list of available locales (search for the
221 I<SEE ALSO> section).  If that fails, try the following command lines:
222
223         locale -a
224
225         nlsinfo
226
227         ls /usr/lib/nls/loc
228
229         ls /usr/lib/locale
230
231         ls /usr/lib/nls
232
233         ls /usr/share/locale
234
235 and see whether they list something resembling these
236
237         en_US.ISO8859-1     de_DE.ISO8859-1     ru_RU.ISO8859-5
238         en_US.iso88591      de_DE.iso88591      ru_RU.iso88595
239         en_US               de_DE               ru_RU
240         en                  de                  ru
241         english             german              russian
242         english.iso88591    german.iso88591     russian.iso88595
243         english.roman8                          russian.koi8r
244
245 Sadly, even though the calling interface for setlocale() has been
246 standardized, names of locales and the directories where the
247 configuration resides have not been.  The basic form of the name is
248 I<language_territory>B<.>I<codeset>, but the latter parts after
249 I<language> are not always present.  The I<language> and I<country>
250 are usually from the standards B<ISO 3166> and B<ISO 639>, the
251 two-letter abbreviations for the countries and the languages of the
252 world, respectively.  The I<codeset> part often mentions some B<ISO
253 8859> character set, the Latin codesets.  For example, C<ISO 8859-1>
254 is the so-called "Western European codeset" that can be used to encode
255 most Western European languages adequately.  Again, there are several
256 ways to write even the name of that one standard.  Lamentably.
257
258 Two special locales are worth particular mention: "C" and "POSIX".
259 Currently these are effectively the same locale: the difference is
260 mainly that the first one is defined by the C standard, the second by
261 the POSIX standard.  They define the B<default locale> in which
262 every program starts in the absence of locale information in its
263 environment.  (The I<default> default locale, if you will.)  Its language
264 is (American) English and its character codeset ASCII.
265 B<Warning>. The C locale delivered by some vendors may not
266 actually exactly match what the C standard calls for.  So beware.
267
268 B<NOTE>: Not all systems have the "POSIX" locale (not all systems are
269 POSIX-conformant), so use "C" when you need explicitly to specify this
270 default locale.
271
272 =head2 LOCALE PROBLEMS
273
274 You may encounter the following warning message at Perl startup:
275
276         perl: warning: Setting locale failed.
277         perl: warning: Please check that your locale settings:
278                 LC_ALL = "En_US",
279                 LANG = (unset)
280             are supported and installed on your system.
281         perl: warning: Falling back to the standard locale ("C").
282
283 This means that your locale settings had LC_ALL set to "En_US" and
284 LANG exists but has no value.  Perl tried to believe you but could not.
285 Instead, Perl gave up and fell back to the "C" locale, the default locale
286 that is supposed to work no matter what.  This usually means your locale
287 settings were wrong, they mention locales your system has never heard
288 of, or the locale installation in your system has problems (for example,
289 some system files are broken or missing).  There are quick and temporary
290 fixes to these problems, as well as more thorough and lasting fixes.
291
292 =head2 Temporarily fixing locale problems
293
294 The two quickest fixes are either to render Perl silent about any
295 locale inconsistencies or to run Perl under the default locale "C".
296
297 Perl's moaning about locale problems can be silenced by setting the
298 environment variable PERL_BADLANG to a zero value, for example "0".
299 This method really just sweeps the problem under the carpet: you tell
300 Perl to shut up even when Perl sees that something is wrong.  Do not
301 be surprised if later something locale-dependent misbehaves.
302
303 Perl can be run under the "C" locale by setting the environment
304 variable LC_ALL to "C".  This method is perhaps a bit more civilized
305 than the PERL_BADLANG approach, but setting LC_ALL (or
306 other locale variables) may affect other programs as well, not just
307 Perl.  In particular, external programs run from within Perl will see
308 these changes.  If you make the new settings permanent (read on), all
309 programs you run see the changes.  See L<"ENVIRONMENT"> for
310 the full list of relevant environment variables and L<USING LOCALES>
311 for their effects in Perl.  Effects in other programs are 
312 easily deducible.  For example, the variable LC_COLLATE may well affect
313 your B<sort> program (or whatever the program that arranges "records"
314 alphabetically in your system is called).
315
316 You can test out changing these variables temporarily, and if the
317 new settings seem to help, put those settings into your shell startup
318 files.  Consult your local documentation for the exact details.  For in
319 Bourne-like shells (B<sh>, B<ksh>, B<bash>, B<zsh>):
320
321         LC_ALL=en_US.ISO8859-1
322         export LC_ALL
323
324 This assumes that we saw the locale "en_US.ISO8859-1" using the commands
325 discussed above.  We decided to try that instead of the above faulty
326 locale "En_US"--and in Cshish shells (B<csh>, B<tcsh>)
327
328         setenv LC_ALL en_US.ISO8859-1
329
330 or if you have the "env" application you can do in any shell
331
332         env LC_ALL=en_US.ISO8859-1 perl ...
333
334 If you do not know what shell you have, consult your local
335 helpdesk or the equivalent.
336
337 =head2 Permanently fixing locale problems
338
339 The slower but superior fixes are when you may be able to yourself
340 fix the misconfiguration of your own environment variables.  The
341 mis(sing)configuration of the whole system's locales usually requires
342 the help of your friendly system administrator.
343
344 First, see earlier in this document about L<Finding locales>.  That tells
345 how to find which locales are really supported--and more importantly,
346 installed--on your system.  In our example error message, environment
347 variables affecting the locale are listed in the order of decreasing
348 importance (and unset variables do not matter).  Therefore, having
349 LC_ALL set to "En_US" must have been the bad choice, as shown by the
350 error message.  First try fixing locale settings listed first.
351
352 Second, if using the listed commands you see something B<exactly>
353 (prefix matches do not count and case usually counts) like "En_US"
354 without the quotes, then you should be okay because you are using a
355 locale name that should be installed and available in your system.
356 In this case, see L<Permanently fixing your system's locale configuration>.
357
358 =head2 Permanently fixing your system's locale configuration
359
360 This is when you see something like:
361
362         perl: warning: Please check that your locale settings:
363                 LC_ALL = "En_US",
364                 LANG = (unset)
365             are supported and installed on your system.
366
367 but then cannot see that "En_US" listed by the above-mentioned
368 commands.  You may see things like "en_US.ISO8859-1", but that isn't
369 the same.  In this case, try running under a locale
370 that you can list and which somehow matches what you tried.  The
371 rules for matching locale names are a bit vague because
372 standardization is weak in this area.  See again the 
373 L<Finding locales> about general rules.
374
375 =head2 Fixing system locale configuration
376
377 Contact a system administrator (preferably your own) and report the exact
378 error message you get, and ask them to read this same documentation you
379 are now reading.  They should be able to check whether there is something
380 wrong with the locale configuration of the system.  The L<Finding locales>
381 section is unfortunately a bit vague about the exact commands and places
382 because these things are not that standardized.
383
384 =head2 The localeconv function
385
386 The POSIX::localeconv() function allows you to get particulars of the
387 locale-dependent numeric formatting information specified by the current
388 C<LC_NUMERIC> and C<LC_MONETARY> locales.  (If you just want the name of
389 the current locale for a particular category, use POSIX::setlocale()
390 with a single parameter--see L<The setlocale function>.)
391
392         use POSIX qw(locale_h);
393
394         # Get a reference to a hash of locale-dependent info
395         $locale_values = localeconv();
396
397         # Output sorted list of the values
398         for (sort keys %$locale_values) {
399             printf "%-20s = %s\n", $_, $locale_values->{$_}
400         }
401
402 localeconv() takes no arguments, and returns B<a reference to> a hash.
403 The keys of this hash are variable names for formatting, such as
404 C<decimal_point> and C<thousands_sep>.  The values are the
405 corresponding, er, values.  See L<POSIX/localeconv> for a longer
406 example listing the categories an implementation might be expected to
407 provide; some provide more and others fewer.  You don't need an
408 explicit C<use locale>, because localeconv() always observes the
409 current locale.
410
411 Here's a simple-minded example program that rewrites its command-line
412 parameters as integers correctly formatted in the current locale:
413
414         # See comments in previous example
415         require 5.004;
416         use POSIX qw(locale_h);
417
418         # Get some of locale's numeric formatting parameters
419         my ($thousands_sep, $grouping) =
420              @{localeconv()}{'thousands_sep', 'grouping'};
421
422         # Apply defaults if values are missing
423         $thousands_sep = ',' unless $thousands_sep;
424
425         # grouping and mon_grouping are packed lists
426         # of small integers (characters) telling the
427         # grouping (thousand_seps and mon_thousand_seps
428         # being the group dividers) of numbers and
429         # monetary quantities.  The integers' meanings:
430         # 255 means no more grouping, 0 means repeat
431         # the previous grouping, 1-254 means use that
432         # as the current grouping.  Grouping goes from
433         # right to left (low to high digits).  In the
434         # below we cheat slightly by never using anything
435         # else than the first grouping (whatever that is).
436         if ($grouping) {
437             @grouping = unpack("C*", $grouping);
438         } else {
439             @grouping = (3);
440         }
441
442         # Format command line params for current locale
443         for (@ARGV) {
444             $_ = int;    # Chop non-integer part
445             1 while
446             s/(\d)(\d{$grouping[0]}($|$thousands_sep))/$1$thousands_sep$2/;
447             print "$_";
448         }
449         print "\n";
450
451 =head2 I18N::Langinfo
452
453 Another interface for querying locale-dependent information is the
454 I18N::Langinfo::langinfo() function, available at least in Unix-like
455 systems and VMS.
456
457 The following example will import the langinfo() function itself and
458 three constants to be used as arguments to langinfo(): a constant for
459 the abbreviated first day of the week (the numbering starts from
460 Sunday = 1) and two more constants for the affirmative and negative
461 answers for a yes/no question in the current locale.
462
463     use I18N::Langinfo qw(langinfo ABDAY_1 YESSTR NOSTR);
464
465     my ($abday_1, $yesstr, $nostr) = map { langinfo } qw(ABDAY_1 YESSTR NOSTR);
466
467     print "$abday_1? [$yesstr/$nostr] ";
468
469 In other words, in the "C" (or English) locale the above will probably
470 print something like:
471
472     Sun? [yes/no] 
473
474 See L<I18N::Langinfo> for more information.
475
476 =head1 LOCALE CATEGORIES
477
478 The following subsections describe basic locale categories.  Beyond these,
479 some combination categories allow manipulation of more than one
480 basic category at a time.  See L<"ENVIRONMENT"> for a discussion of these.
481
482 =head2 Category LC_COLLATE: Collation
483
484 In the scope of S<C<use locale>>, Perl looks to the C<LC_COLLATE>
485 environment variable to determine the application's notions on collation
486 (ordering) of characters.  For example, "b" follows "a" in Latin
487 alphabets, but where do "E<aacute>" and "E<aring>" belong?  And while
488 "color" follows "chocolate" in English, what about in Spanish?
489
490 The following collations all make sense and you may meet any of them
491 if you "use locale".
492
493         A B C D E a b c d e
494         A a B b C c D d E e
495         a A b B c C d D e E
496         a b c d e A B C D E
497
498 Here is a code snippet to tell what "word"
499 characters are in the current locale, in that locale's order:
500
501         use locale;
502         print +(sort grep /\w/, map { chr } 0..255), "\n";
503
504 Compare this with the characters that you see and their order if you
505 state explicitly that the locale should be ignored:
506
507         no locale;
508         print +(sort grep /\w/, map { chr } 0..255), "\n";
509
510 This machine-native collation (which is what you get unless S<C<use
511 locale>> has appeared earlier in the same block) must be used for
512 sorting raw binary data, whereas the locale-dependent collation of the
513 first example is useful for natural text.
514
515 As noted in L<USING LOCALES>, C<cmp> compares according to the current
516 collation locale when C<use locale> is in effect, but falls back to a
517 char-by-char comparison for strings that the locale says are equal. You
518 can use POSIX::strcoll() if you don't want this fall-back:
519
520         use POSIX qw(strcoll);
521         $equal_in_locale =
522             !strcoll("space and case ignored", "SpaceAndCaseIgnored");
523
524 $equal_in_locale will be true if the collation locale specifies a
525 dictionary-like ordering that ignores space characters completely and
526 which folds case.
527
528 If you have a single string that you want to check for "equality in
529 locale" against several others, you might think you could gain a little
530 efficiency by using POSIX::strxfrm() in conjunction with C<eq>:
531
532         use POSIX qw(strxfrm);
533         $xfrm_string = strxfrm("Mixed-case string");
534         print "locale collation ignores spaces\n"
535             if $xfrm_string eq strxfrm("Mixed-casestring");
536         print "locale collation ignores hyphens\n"
537             if $xfrm_string eq strxfrm("Mixedcase string");
538         print "locale collation ignores case\n"
539             if $xfrm_string eq strxfrm("mixed-case string");
540
541 strxfrm() takes a string and maps it into a transformed string for use
542 in char-by-char comparisons against other transformed strings during
543 collation.  "Under the hood", locale-affected Perl comparison operators
544 call strxfrm() for both operands, then do a char-by-char
545 comparison of the transformed strings.  By calling strxfrm() explicitly
546 and using a non locale-affected comparison, the example attempts to save
547 a couple of transformations.  But in fact, it doesn't save anything: Perl
548 magic (see L<perlguts/Magic Variables>) creates the transformed version of a
549 string the first time it's needed in a comparison, then keeps this version around
550 in case it's needed again.  An example rewritten the easy way with
551 C<cmp> runs just about as fast.  It also copes with null characters
552 embedded in strings; if you call strxfrm() directly, it treats the first
553 null it finds as a terminator.  don't expect the transformed strings
554 it produces to be portable across systems--or even from one revision
555 of your operating system to the next.  In short, don't call strxfrm()
556 directly: let Perl do it for you.
557
558 Note: C<use locale> isn't shown in some of these examples because it isn't
559 needed: strcoll() and strxfrm() exist only to generate locale-dependent
560 results, and so always obey the current C<LC_COLLATE> locale.
561
562 =head2 Category LC_CTYPE: Character Types
563
564 In the scope of S<C<use locale>>, Perl obeys the C<LC_CTYPE> locale
565 setting.  This controls the application's notion of which characters are
566 alphabetic.  This affects Perl's C<\w> regular expression metanotation,
567 which stands for alphanumeric characters--that is, alphabetic,
568 numeric, and including other special characters such as the underscore or
569 hyphen.  (Consult L<perlre> for more information about
570 regular expressions.)  Thanks to C<LC_CTYPE>, depending on your locale
571 setting, characters like "E<aelig>", "E<eth>", "E<szlig>", and
572 "E<oslash>" may be understood as C<\w> characters.
573
574 The C<LC_CTYPE> locale also provides the map used in transliterating
575 characters between lower and uppercase.  This affects the case-mapping
576 functions--lc(), lcfirst, uc(), and ucfirst(); case-mapping
577 interpolation with C<\l>, C<\L>, C<\u>, or C<\U> in double-quoted strings
578 and C<s///> substitutions; and case-independent regular expression
579 pattern matching using the C<i> modifier.
580
581 Finally, C<LC_CTYPE> affects the POSIX character-class test
582 functions--isalpha(), islower(), and so on.  For example, if you move
583 from the "C" locale to a 7-bit Scandinavian one, you may find--possibly
584 to your surprise--that "|" moves from the ispunct() class to isalpha().
585
586 B<Note:> A broken or malicious C<LC_CTYPE> locale definition may result
587 in clearly ineligible characters being considered to be alphanumeric by
588 your application.  For strict matching of (mundane) ASCII letters and
589 digits--for example, in command strings--locale-aware applications
590 should use C<\w> with the C</a> regular expression modifier.  See L<"SECURITY">.
591
592 =head2 Category LC_NUMERIC: Numeric Formatting
593
594 After a proper POSIX::setlocale() call, Perl obeys the C<LC_NUMERIC>
595 locale information, which controls an application's idea of how numbers
596 should be formatted for human readability by the printf(), sprintf(), and
597 write() functions. String-to-numeric conversion by the POSIX::strtod()
598 function is also affected.  In most implementations the only effect is to
599 change the character used for the decimal point--perhaps from "."  to ",".
600 These functions aren't aware of such niceties as thousands separation and
601 so on. (See L<The localeconv function> if you care about these things.)
602
603 Output produced by print() is also affected by the current locale: it
604 corresponds to what you'd get from printf() in the "C" locale.  The
605 same is true for Perl's internal conversions between numeric and
606 string formats:
607
608         use POSIX qw(strtod setlocale LC_NUMERIC);
609
610         setlocale LC_NUMERIC, "";
611
612         $n = 5/2;   # Assign numeric 2.5 to $n
613
614         $a = " $n"; # Locale-dependent conversion to string
615
616         print "half five is $n\n";       # Locale-dependent output
617
618         printf "half five is %g\n", $n;  # Locale-dependent output
619
620         print "DECIMAL POINT IS COMMA\n"
621             if $n == (strtod("2,5"))[0]; # Locale-dependent conversion
622
623 See also L<I18N::Langinfo> and C<RADIXCHAR>.
624
625 =head2 Category LC_MONETARY: Formatting of monetary amounts
626
627 The C standard defines the C<LC_MONETARY> category, but not a function
628 that is affected by its contents.  (Those with experience of standards
629 committees will recognize that the working group decided to punt on the
630 issue.)  Consequently, Perl takes no notice of it.  If you really want
631 to use C<LC_MONETARY>, you can query its contents--see 
632 L<The localeconv function>--and use the information that it returns in your 
633 application's own formatting of currency amounts.  However, you may well 
634 find that the information, voluminous and complex though it may be, still 
635 does not quite meet your requirements: currency formatting is a hard nut 
636 to crack.
637
638 See also L<I18N::Langinfo> and C<CRNCYSTR>.
639
640 =head2 LC_TIME
641
642 Output produced by POSIX::strftime(), which builds a formatted
643 human-readable date/time string, is affected by the current C<LC_TIME>
644 locale.  Thus, in a French locale, the output produced by the C<%B>
645 format element (full month name) for the first month of the year would
646 be "janvier".  Here's how to get a list of long month names in the
647 current locale:
648
649         use POSIX qw(strftime);
650         for (0..11) {
651             $long_month_name[$_] =
652                 strftime("%B", 0, 0, 0, 1, $_, 96);
653         }
654
655 Note: C<use locale> isn't needed in this example: as a function that
656 exists only to generate locale-dependent results, strftime() always
657 obeys the current C<LC_TIME> locale.
658
659 See also L<I18N::Langinfo> and C<ABDAY_1>..C<ABDAY_7>, C<DAY_1>..C<DAY_7>,
660 C<ABMON_1>..C<ABMON_12>, and C<ABMON_1>..C<ABMON_12>.
661
662 =head2 Other categories
663
664 The remaining locale category, C<LC_MESSAGES> (possibly supplemented
665 by others in particular implementations) is not currently used by
666 Perl--except possibly to affect the behavior of library functions
667 called by extensions outside the standard Perl distribution and by the
668 operating system and its utilities.  Note especially that the string
669 value of C<$!> and the error messages given by external utilities may
670 be changed by C<LC_MESSAGES>.  If you want to have portable error
671 codes, use C<%!>.  See L<Errno>.
672
673 =head1 SECURITY
674
675 Although the main discussion of Perl security issues can be found in
676 L<perlsec>, a discussion of Perl's locale handling would be incomplete
677 if it did not draw your attention to locale-dependent security issues.
678 Locales--particularly on systems that allow unprivileged users to
679 build their own locales--are untrustworthy.  A malicious (or just plain
680 broken) locale can make a locale-aware application give unexpected
681 results.  Here are a few possibilities:
682
683 =over 4
684
685 =item *
686
687 Regular expression checks for safe file names or mail addresses using
688 C<\w> may be spoofed by an C<LC_CTYPE> locale that claims that
689 characters such as "E<gt>" and "|" are alphanumeric.
690
691 =item *
692
693 String interpolation with case-mapping, as in, say, C<$dest =
694 "C:\U$name.$ext">, may produce dangerous results if a bogus LC_CTYPE
695 case-mapping table is in effect.
696
697 =item *
698
699 A sneaky C<LC_COLLATE> locale could result in the names of students with
700 "D" grades appearing ahead of those with "A"s.
701
702 =item *
703
704 An application that takes the trouble to use information in
705 C<LC_MONETARY> may format debits as if they were credits and vice versa
706 if that locale has been subverted.  Or it might make payments in US
707 dollars instead of Hong Kong dollars.
708
709 =item *
710
711 The date and day names in dates formatted by strftime() could be
712 manipulated to advantage by a malicious user able to subvert the
713 C<LC_DATE> locale.  ("Look--it says I wasn't in the building on
714 Sunday.")
715
716 =back
717
718 Such dangers are not peculiar to the locale system: any aspect of an
719 application's environment which may be modified maliciously presents
720 similar challenges.  Similarly, they are not specific to Perl: any
721 programming language that allows you to write programs that take
722 account of their environment exposes you to these issues.
723
724 Perl cannot protect you from all possibilities shown in the
725 examples--there is no substitute for your own vigilance--but, when
726 C<use locale> is in effect, Perl uses the tainting mechanism (see
727 L<perlsec>) to mark string results that become locale-dependent, and
728 which may be untrustworthy in consequence.  Here is a summary of the
729 tainting behavior of operators and functions that may be affected by
730 the locale:
731
732 =over 4
733
734 =item  *
735
736 B<Comparison operators> (C<lt>, C<le>, C<ge>, C<gt> and C<cmp>):
737
738 Scalar true/false (or less/equal/greater) result is never tainted.
739
740 =item  *
741
742 B<Case-mapping interpolation> (with C<\l>, C<\L>, C<\u> or C<\U>)
743
744 Result string containing interpolated material is tainted if
745 C<use locale> is in effect.
746
747 =item  *
748
749 B<Matching operator> (C<m//>):
750
751 Scalar true/false result never tainted.
752
753 Subpatterns, either delivered as a list-context result or as $1 etc.
754 are tainted if C<use locale> is in effect, and the subpattern regular
755 expression contains C<\w> (to match an alphanumeric character), C<\W>
756 (non-alphanumeric character), C<\s> (whitespace character), or C<\S>
757 (non whitespace character).  The matched-pattern variable, $&, $`
758 (pre-match), $' (post-match), and $+ (last match) are also tainted if
759 C<use locale> is in effect and the regular expression contains C<\w>,
760 C<\W>, C<\s>, or C<\S>.
761
762 =item  *
763
764 B<Substitution operator> (C<s///>):
765
766 Has the same behavior as the match operator.  Also, the left
767 operand of C<=~> becomes tainted when C<use locale> in effect
768 if modified as a result of a substitution based on a regular
769 expression match involving C<\w>, C<\W>, C<\s>, or C<\S>; or of
770 case-mapping with C<\l>, C<\L>,C<\u> or C<\U>.
771
772 =item *
773
774 B<Output formatting functions> (printf() and write()):
775
776 Results are never tainted because otherwise even output from print,
777 for example C<print(1/7)>, should be tainted if C<use locale> is in
778 effect.
779
780 =item *
781
782 B<Case-mapping functions> (lc(), lcfirst(), uc(), ucfirst()):
783
784 Results are tainted if C<use locale> is in effect.
785
786 =item *
787
788 B<POSIX locale-dependent functions> (localeconv(), strcoll(),
789 strftime(), strxfrm()):
790
791 Results are never tainted.
792
793 =item *
794
795 B<POSIX character class tests> (isalnum(), isalpha(), isdigit(),
796 isgraph(), islower(), isprint(), ispunct(), isspace(), isupper(),
797 isxdigit()):
798
799 True/false results are never tainted.
800
801 =back
802
803 Three examples illustrate locale-dependent tainting.
804 The first program, which ignores its locale, won't run: a value taken
805 directly from the command line may not be used to name an output file
806 when taint checks are enabled.
807
808         #/usr/local/bin/perl -T
809         # Run with taint checking
810
811         # Command line sanity check omitted...
812         $tainted_output_file = shift;
813
814         open(F, ">$tainted_output_file")
815             or warn "Open of $untainted_output_file failed: $!\n";
816
817 The program can be made to run by "laundering" the tainted value through
818 a regular expression: the second example--which still ignores locale
819 information--runs, creating the file named on its command line
820 if it can.
821
822         #/usr/local/bin/perl -T
823
824         $tainted_output_file = shift;
825         $tainted_output_file =~ m%[\w/]+%;
826         $untainted_output_file = $&;
827
828         open(F, ">$untainted_output_file")
829             or warn "Open of $untainted_output_file failed: $!\n";
830
831 Compare this with a similar but locale-aware program:
832
833         #/usr/local/bin/perl -T
834
835         $tainted_output_file = shift;
836         use locale;
837         $tainted_output_file =~ m%[\w/]+%;
838         $localized_output_file = $&;
839
840         open(F, ">$localized_output_file")
841             or warn "Open of $localized_output_file failed: $!\n";
842
843 This third program fails to run because $& is tainted: it is the result
844 of a match involving C<\w> while C<use locale> is in effect.
845
846 =head1 ENVIRONMENT
847
848 =over 12
849
850 =item PERL_BADLANG
851
852 A string that can suppress Perl's warning about failed locale settings
853 at startup.  Failure can occur if the locale support in the operating
854 system is lacking (broken) in some way--or if you mistyped the name of
855 a locale when you set up your environment.  If this environment
856 variable is absent, or has a value that does not evaluate to integer
857 zero--that is, "0" or ""-- Perl will complain about locale setting
858 failures.
859
860 B<NOTE>: PERL_BADLANG only gives you a way to hide the warning message.
861 The message tells about some problem in your system's locale support,
862 and you should investigate what the problem is.
863
864 =back
865
866 The following environment variables are not specific to Perl: They are
867 part of the standardized (ISO C, XPG4, POSIX 1.c) setlocale() method
868 for controlling an application's opinion on data.
869
870 =over 12
871
872 =item LC_ALL
873
874 C<LC_ALL> is the "override-all" locale environment variable. If
875 set, it overrides all the rest of the locale environment variables.
876
877 =item LANGUAGE
878
879 B<NOTE>: C<LANGUAGE> is a GNU extension, it affects you only if you
880 are using the GNU libc.  This is the case if you are using e.g. Linux.
881 If you are using "commercial" Unixes you are most probably I<not>
882 using GNU libc and you can ignore C<LANGUAGE>.
883
884 However, in the case you are using C<LANGUAGE>: it affects the
885 language of informational, warning, and error messages output by
886 commands (in other words, it's like C<LC_MESSAGES>) but it has higher
887 priority than C<LC_ALL>.  Moreover, it's not a single value but
888 instead a "path" (":"-separated list) of I<languages> (not locales).
889 See the GNU C<gettext> library documentation for more information.
890
891 =item LC_CTYPE
892
893 In the absence of C<LC_ALL>, C<LC_CTYPE> chooses the character type
894 locale.  In the absence of both C<LC_ALL> and C<LC_CTYPE>, C<LANG>
895 chooses the character type locale.
896
897 =item LC_COLLATE
898
899 In the absence of C<LC_ALL>, C<LC_COLLATE> chooses the collation
900 (sorting) locale.  In the absence of both C<LC_ALL> and C<LC_COLLATE>,
901 C<LANG> chooses the collation locale.
902
903 =item LC_MONETARY
904
905 In the absence of C<LC_ALL>, C<LC_MONETARY> chooses the monetary
906 formatting locale.  In the absence of both C<LC_ALL> and C<LC_MONETARY>,
907 C<LANG> chooses the monetary formatting locale.
908
909 =item LC_NUMERIC
910
911 In the absence of C<LC_ALL>, C<LC_NUMERIC> chooses the numeric format
912 locale.  In the absence of both C<LC_ALL> and C<LC_NUMERIC>, C<LANG>
913 chooses the numeric format.
914
915 =item LC_TIME
916
917 In the absence of C<LC_ALL>, C<LC_TIME> chooses the date and time
918 formatting locale.  In the absence of both C<LC_ALL> and C<LC_TIME>,
919 C<LANG> chooses the date and time formatting locale.
920
921 =item LANG
922
923 C<LANG> is the "catch-all" locale environment variable. If it is set, it
924 is used as the last resort after the overall C<LC_ALL> and the
925 category-specific C<LC_...>.
926
927 =back
928
929 =head2 Examples
930
931 The LC_NUMERIC controls the numeric output:
932
933         use locale;
934         use POSIX qw(locale_h); # Imports setlocale() and the LC_ constants.
935         setlocale(LC_NUMERIC, "fr_FR") or die "Pardon";
936         printf "%g\n", 1.23; # If the "fr_FR" succeeded, probably shows 1,23.
937
938 and also how strings are parsed by POSIX::strtod() as numbers:
939
940         use locale;
941         use POSIX qw(locale_h strtod);
942         setlocale(LC_NUMERIC, "de_DE") or die "Entschuldigung";
943         my $x = strtod("2,34") + 5;
944         print $x, "\n"; # Probably shows 7,34.
945
946 =head1 NOTES
947
948 =head2 Backward compatibility
949
950 Versions of Perl prior to 5.004 B<mostly> ignored locale information,
951 generally behaving as if something similar to the C<"C"> locale were
952 always in force, even if the program environment suggested otherwise
953 (see L<The setlocale function>).  By default, Perl still behaves this
954 way for backward compatibility.  If you want a Perl application to pay
955 attention to locale information, you B<must> use the S<C<use locale>>
956 pragma (see L<The use locale pragma>) or, in the unlikely event
957 that you want to do so for just pattern matching, the
958 C</l> regular expression modifier (see L<perlre/Character set
959 modifiers>) to instruct it to do so.
960
961 Versions of Perl from 5.002 to 5.003 did use the C<LC_CTYPE>
962 information if available; that is, C<\w> did understand what
963 were the letters according to the locale environment variables.
964 The problem was that the user had no control over the feature:
965 if the C library supported locales, Perl used them.
966
967 =head2 I18N:Collate obsolete
968
969 In versions of Perl prior to 5.004, per-locale collation was possible
970 using the C<I18N::Collate> library module.  This module is now mildly
971 obsolete and should be avoided in new applications.  The C<LC_COLLATE>
972 functionality is now integrated into the Perl core language: One can
973 use locale-specific scalar data completely normally with C<use locale>,
974 so there is no longer any need to juggle with the scalar references of
975 C<I18N::Collate>.
976
977 =head2 Sort speed and memory use impacts
978
979 Comparing and sorting by locale is usually slower than the default
980 sorting; slow-downs of two to four times have been observed.  It will
981 also consume more memory: once a Perl scalar variable has participated
982 in any string comparison or sorting operation obeying the locale
983 collation rules, it will take 3-15 times more memory than before.  (The
984 exact multiplier depends on the string's contents, the operating system
985 and the locale.) These downsides are dictated more by the operating
986 system's implementation of the locale system than by Perl.
987
988 =head2 write() and LC_NUMERIC
989
990 If a program's environment specifies an LC_NUMERIC locale and C<use
991 locale> is in effect when the format is declared, the locale is used
992 to specify the decimal point character in formatted output.  Formatted
993 output cannot be controlled by C<use locale> at the time when write()
994 is called.
995
996 =head2 Freely available locale definitions
997
998 There is a large collection of locale definitions at:
999
1000   http://std.dkuug.dk/i18n/WG15-collection/locales/
1001
1002 You should be aware that it is
1003 unsupported, and is not claimed to be fit for any purpose.  If your
1004 system allows installation of arbitrary locales, you may find the
1005 definitions useful as they are, or as a basis for the development of
1006 your own locales.
1007
1008 =head2 I18n and l10n
1009
1010 "Internationalization" is often abbreviated as B<i18n> because its first
1011 and last letters are separated by eighteen others.  (You may guess why
1012 the internalin ... internaliti ... i18n tends to get abbreviated.)  In
1013 the same way, "localization" is often abbreviated to B<l10n>.
1014
1015 =head2 An imperfect standard
1016
1017 Internationalization, as defined in the C and POSIX standards, can be
1018 criticized as incomplete, ungainly, and having too large a granularity.
1019 (Locales apply to a whole process, when it would arguably be more useful
1020 to have them apply to a single thread, window group, or whatever.)  They
1021 also have a tendency, like standards groups, to divide the world into
1022 nations, when we all know that the world can equally well be divided
1023 into bankers, bikers, gamers, and so on.
1024
1025 =head1 Unicode and UTF-8
1026
1027 The support of Unicode is new starting from Perl version 5.6, and more fully
1028 implemented in version 5.8 and later.  See L<perluniintro>.  Perl tries to
1029 work with both Unicode and locales--but of course, there are problems.
1030
1031 Perl does not handle multi-byte locales, such as have been used for various
1032 Asian languages, such as Big5 or Shift JIS.  However, the increasingly common
1033 multi-byte UTF-8 locales, if properly implemented, tend to work
1034 reasonably well in Perl, simply because both they and Perl store
1035 characters that take up multiple bytes the same way.
1036
1037 Perl generally takes the tack to use locale rules on code points that can fit
1038 in a single byte, and Unicode rules for those that can't (though this wasn't
1039 uniformly applied prior to Perl 5.14).  This prevents many problems in locales
1040 that aren't UTF-8.  Suppose the locale is ISO8859-7, Greek.  The character at
1041 0xD7 there is a capital Chi. But in the ISO8859-1 locale, Latin1, it is a
1042 multiplication sign.  The POSIX regular expression character class
1043 C<[[:alpha:]]> will magically match 0xD7 in the Greek locale but not in the
1044 Latin one, even if the string is encoded in UTF-8, which would normally imply
1045 Unicode semantics.  (The "U" in UTF-8 stands for Unicode.)
1046
1047 However, there are places where this breaks down.  Certain constructs are
1048 for Unicode only, such as C<\p{Alpha}>.  They assume that 0xD7 always has its
1049 Unicode meaning (or the equivalent on EBCDIC platforms).  Since Latin1 is a
1050 subset of Unicode and 0xD7 is the multiplication sign in both Latin1 and
1051 Unicode, C<\p{Alpha}> will never match it, regardless of locale.  A similar
1052 issue occurs with C<\N{...}>.  It is therefore a bad idea to use C<\p{}> or
1053 C<\N{}> under C<use locale>--I<unless> you can guarantee that the locale will
1054 be a ISO8859-1 or UTF-8 one.  Use POSIX character classes instead.
1055
1056
1057 The same problem ensues if you enable automatic UTF-8-ification of your
1058 standard file handles, default C<open()> layer, and C<@ARGV> on non-ISO8859-1,
1059 non-UTF-8 locales (by using either the B<-C> command line switch or the
1060 C<PERL_UNICODE> environment variable; see L<perlrun>).
1061 Things are read in as UTF-8, which would normally imply a Unicode
1062 interpretation, but the presence of a locale causes them to be interpreted
1063 in that locale instead.  For example, a 0xD7 code point in the Unicode
1064 input, which should mean the multiplication sign, won't be interpreted by
1065 Perl that way under the Greek locale.  Again, this is not a problem
1066 I<provided> you make certain that all locales will always and only be either
1067 an ISO8859-1 or a UTF-8 locale.
1068
1069 Vendor locales are notoriously buggy, and it is difficult for Perl to test
1070 its locale-handling code because this interacts with code that Perl has no
1071 control over; therefore the locale-handling code in Perl may be buggy as
1072 well.  But if you I<do> have locales that work, using them may be
1073 worthwhile for certain specific purposes, as long as you keep in mind the
1074 gotchas already mentioned.  For example, collation runs faster under
1075 locales than under L<Unicode::Collate> (albeit with less flexibility), and
1076 you gain access to such things as the local currency symbol and the names
1077 of the months and days of the week.
1078
1079 =head1 BUGS
1080
1081 =head2 Broken systems
1082
1083 In certain systems, the operating system's locale support
1084 is broken and cannot be fixed or used by Perl.  Such deficiencies can
1085 and will result in mysterious hangs and/or Perl core dumps when
1086 C<use locale> is in effect.  When confronted with such a system,
1087 please report in excruciating detail to <F<perlbug@perl.org>>, and
1088 also contact your vendor: bug fixes may exist for these problems
1089 in your operating system.  Sometimes such bug fixes are called an
1090 operating system upgrade.
1091
1092 =head1 SEE ALSO
1093
1094 L<I18N::Langinfo>, L<perluniintro>, L<perlunicode>, L<open>,
1095 L<POSIX/isalnum>, L<POSIX/isalpha>,
1096 L<POSIX/isdigit>, L<POSIX/isgraph>, L<POSIX/islower>,
1097 L<POSIX/isprint>, L<POSIX/ispunct>, L<POSIX/isspace>,
1098 L<POSIX/isupper>, L<POSIX/isxdigit>, L<POSIX/localeconv>,
1099 L<POSIX/setlocale>, L<POSIX/strcoll>, L<POSIX/strftime>,
1100 L<POSIX/strtod>, L<POSIX/strxfrm>.
1101
1102 =head1 HISTORY
1103
1104 Jarkko Hietaniemi's original F<perli18n.pod> heavily hacked by Dominic
1105 Dunlop, assisted by the perl5-porters.  Prose worked over a bit by
1106 Tom Christiansen, and updated by Perl 5 porters.