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