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