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