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