1PERLLOCALE(1)          Perl Programmers Reference Guide          PERLLOCALE(1)
2
3
4

NAME

6       perllocale - Perl locale handling (internationalization and localiza‐
7       tion)
8

DESCRIPTION

10       Perl supports language-specific notions of data such as "is this a let‐
11       ter", "what is the uppercase equivalent of this letter", and "which of
12       these letters comes first".  These are important issues, especially for
13       languages other than English--but also for English: it would be naieve
14       to imagine that "A-Za-z" defines all the "letters" needed to write in
15       English. Perl is also aware that some character other than '.' may be
16       preferred as a decimal point, and that output date representations may
17       be language-specific.  The process of making an application take
18       account of its users' preferences in such matters is called interna‐
19       tionalization (often abbreviated as i18n); telling such an application
20       about a particular set of preferences is known as localization (l10n).
21
22       Perl can understand language-specific data via the standardized (ISO C,
23       XPG4, POSIX 1.c) method called "the locale system". The locale system
24       is controlled per application using one pragma, one function call, and
25       several environment variables.
26
27       NOTE: This feature is new in Perl 5.004, and does not apply unless an
28       application specifically requests it--see "Backward compatibility".
29       The one exception is that write() now always uses the current locale -
30       see "NOTES".
31

PREPARING TO USE LOCALES

33       If Perl applications are to understand and present your data correctly
34       according a locale of your choice, all of the following must be true:
35
36       ·   Your operating system must support the locale system.  If it does,
37           you should find that the setlocale() function is a documented part
38           of its C library.
39
40       ·   Definitions for locales that you use must be installed.  You, or
41           your system administrator, must make sure that this is the case.
42           The available locales, the location in which they are kept, and the
43           manner in which they are installed all vary from system to system.
44           Some systems provide only a few, hard-wired locales and do not
45           allow more to be added.  Others allow you to add "canned" locales
46           provided by the system supplier.  Still others allow you or the
47           system administrator to define and add arbitrary locales.  (You may
48           have to ask your supplier to provide canned locales that are not
49           delivered with your operating system.)  Read your system documenta‐
50           tion for further illumination.
51
52       ·   Perl must believe that the locale system is supported.  If it does,
53           "perl -V:d_setlocale" will say that the value for "d_setlocale" is
54           "define".
55
56       If you want a Perl application to process and present your data accord‐
57       ing to a particular locale, the application code should include the
58       "use locale" pragma (see "The use locale pragma") where appropriate,
59       and at least one of the following must be true:
60
61       ·   The locale-determining environment variables (see "ENVIRONMENT")
62           must be correctly set up at the time the application is started,
63           either by yourself or by whoever set up your system account.
64
65       ·   The application must set its own locale using the method described
66           in "The setlocale function".
67

USING LOCALES

69       The use locale pragma
70
71       By default, Perl ignores the current locale.  The "use locale" pragma
72       tells Perl to use the current locale for some operations:
73
74       ·   The comparison operators ("lt", "le", "cmp", "ge", and "gt") and
75           the POSIX string collation functions strcoll() and strxfrm() use
76           "LC_COLLATE".  sort() is also affected if used without an explicit
77           comparison function, because it uses "cmp" by default.
78
79           Note: "eq" and "ne" are unaffected by locale: they always perform a
80           char-by-char comparison of their scalar operands.  What's more, if
81           "cmp" finds that its operands are equal according to the collation
82           sequence specified by the current locale, it goes on to perform a
83           char-by-char comparison, and only returns 0 (equal) if the operands
84           are char-for-char identical.  If you really want to know whether
85           two strings--which "eq" and "cmp" may consider different--are equal
86           as far as collation in the locale is concerned, see the discussion
87           in "Category LC_COLLATE: Collation".
88
89       ·   Regular expressions and case-modification functions (uc(), lc(),
90           ucfirst(), and lcfirst()) use "LC_CTYPE"
91
92       ·   The formatting functions (printf(), sprintf() and write()) use
93           "LC_NUMERIC"
94
95       ·   The POSIX date formatting function (strftime()) uses "LC_TIME".
96
97       "LC_COLLATE", "LC_CTYPE", and so on, are discussed further in "LOCALE
98       CATEGORIES".
99
100       The default behavior is restored with the "no locale" pragma, or upon
101       reaching the end of block enclosing "use locale".
102
103       The string result of any operation that uses locale information is
104       tainted, as it is possible for a locale to be untrustworthy.  See
105       "SECURITY".
106
107       The setlocale function
108
109       You can switch locales as often as you wish at run time with the
110       POSIX::setlocale() function:
111
112               # This functionality not usable prior to Perl 5.004
113               require 5.004;
114
115               # Import locale-handling tool set from POSIX module.
116               # This example uses: setlocale -- the function call
117               #                    LC_CTYPE -- explained below
118               use POSIX qw(locale_h);
119
120               # query and save the old locale
121               $old_locale = setlocale(LC_CTYPE);
122
123               setlocale(LC_CTYPE, "fr_CA.ISO8859-1");
124               # LC_CTYPE now in locale "French, Canada, codeset ISO 8859-1"
125
126               setlocale(LC_CTYPE, "");
127               # LC_CTYPE now reset to default defined by LC_ALL/LC_CTYPE/LANG
128               # environment variables.  See below for documentation.
129
130               # restore the old locale
131               setlocale(LC_CTYPE, $old_locale);
132
133       The first argument of setlocale() gives the category, the second the
134       locale.  The category tells in what aspect of data processing you want
135       to apply locale-specific rules.  Category names are discussed in
136       "LOCALE CATEGORIES" and "ENVIRONMENT".  The locale is the name of a
137       collection of customization information corresponding to a particular
138       combination of language, country or territory, and codeset.  Read on
139       for hints on the naming of locales: not all systems name locales as in
140       the example.
141
142       If no second argument is provided and the category is something else
143       than LC_ALL, the function returns a string naming the current locale
144       for the category.  You can use this value as the second argument in a
145       subsequent call to setlocale().
146
147       If no second argument is provided and the category is LC_ALL, the
148       result is implementation-dependent.  It may be a string of concatenated
149       locales names (separator also implementation-dependent) or a single
150       locale name.  Please consult your setlocale(3) for details.
151
152       If a second argument is given and it corresponds to a valid locale, the
153       locale for the category is set to that value, and the function returns
154       the now-current locale value.  You can then use this in yet another
155       call to setlocale().  (In some implementations, the return value may
156       sometimes differ from the value you gave as the second argument--think
157       of it as an alias for the value you gave.)
158
159       As the example shows, if the second argument is an empty string, the
160       category's locale is returned to the default specified by the corre‐
161       sponding environment variables.  Generally, this results in a return to
162       the default that was in force when Perl started up: changes to the
163       environment made by the application after startup may or may not be
164       noticed, depending on your system's C library.
165
166       If the second argument does not correspond to a valid locale, the
167       locale for the category is not changed, and the function returns undef.
168
169       For further information about the categories, consult setlocale(3).
170
171       Finding locales
172
173       For locales available in your system, consult also setlocale(3) to see
174       whether it leads to the list of available locales (search for the SEE
175       ALSO section).  If that fails, try the following command lines:
176
177               locale -a
178
179               nlsinfo
180
181               ls /usr/lib/nls/loc
182
183               ls /usr/lib/locale
184
185               ls /usr/lib/nls
186
187               ls /usr/share/locale
188
189       and see whether they list something resembling these
190
191               en_US.ISO8859-1     de_DE.ISO8859-1     ru_RU.ISO8859-5
192               en_US.iso88591      de_DE.iso88591      ru_RU.iso88595
193               en_US               de_DE               ru_RU
194               en                  de                  ru
195               english             german              russian
196               english.iso88591    german.iso88591     russian.iso88595
197               english.roman8                          russian.koi8r
198
199       Sadly, even though the calling interface for setlocale() has been stan‐
200       dardized, names of locales and the directories where the configuration
201       resides have not been.  The basic form of the name is language_terri‐
202       tory.codeset, but the latter parts after language are not always
203       present.  The language and country are usually from the standards ISO
204       3166 and ISO 639, the two-letter abbreviations for the countries and
205       the languages of the world, respectively.  The codeset part often men‐
206       tions some ISO 8859 character set, the Latin codesets.  For example,
207       "ISO 8859-1" is the so-called "Western European codeset" that can be
208       used to encode most Western European languages adequately.  Again,
209       there are several ways to write even the name of that one standard.
210       Lamentably.
211
212       Two special locales are worth particular mention: "C" and "POSIX".
213       Currently these are effectively the same locale: the difference is
214       mainly that the first one is defined by the C standard, the second by
215       the POSIX standard.  They define the default locale in which every pro‐
216       gram starts in the absence of locale information in its environment.
217       (The default default locale, if you will.)  Its language is (American)
218       English and its character codeset ASCII.
219
220       NOTE: Not all systems have the "POSIX" locale (not all systems are
221       POSIX-conformant), so use "C" when you need explicitly to specify this
222       default locale.
223
224       LOCALE PROBLEMS
225
226       You may encounter the following warning message at Perl startup:
227
228               perl: warning: Setting locale failed.
229               perl: warning: Please check that your locale settings:
230                       LC_ALL = "En_US",
231                       LANG = (unset)
232                   are supported and installed on your system.
233               perl: warning: Falling back to the standard locale ("C").
234
235       This means that your locale settings had LC_ALL set to "En_US" and LANG
236       exists but has no value.  Perl tried to believe you but could not.
237       Instead, Perl gave up and fell back to the "C" locale, the default
238       locale that is supposed to work no matter what.  This usually means
239       your locale settings were wrong, they mention locales your system has
240       never heard of, or the locale installation in your system has problems
241       (for example, some system files are broken or missing).  There are
242       quick and temporary fixes to these problems, as well as more thorough
243       and lasting fixes.
244
245       Temporarily fixing locale problems
246
247       The two quickest fixes are either to render Perl silent about any
248       locale inconsistencies or to run Perl under the default locale "C".
249
250       Perl's moaning about locale problems can be silenced by setting the
251       environment variable PERL_BADLANG to a zero value, for example "0".
252       This method really just sweeps the problem under the carpet: you tell
253       Perl to shut up even when Perl sees that something is wrong.  Do not be
254       surprised if later something locale-dependent misbehaves.
255
256       Perl can be run under the "C" locale by setting the environment vari‐
257       able LC_ALL to "C".  This method is perhaps a bit more civilized than
258       the PERL_BADLANG approach, but setting LC_ALL (or other locale vari‐
259       ables) may affect other programs as well, not just Perl.  In particu‐
260       lar, external programs run from within Perl will see these changes.  If
261       you make the new settings permanent (read on), all programs you run see
262       the changes.  See ENVIRONMENT for the full list of relevant environment
263       variables and "USING LOCALES" for their effects in Perl.  Effects in
264       other programs are easily deducible.  For example, the variable LC_COL‐
265       LATE may well affect your sort program (or whatever the program that
266       arranges "records" alphabetically in your system is called).
267
268       You can test out changing these variables temporarily, and if the new
269       settings seem to help, put those settings into your shell startup
270       files.  Consult your local documentation for the exact details.  For in
271       Bourne-like shells (sh, ksh, bash, zsh):
272
273               LC_ALL=en_US.ISO8859-1
274               export LC_ALL
275
276       This assumes that we saw the locale "en_US.ISO8859-1" using the com‐
277       mands discussed above.  We decided to try that instead of the above
278       faulty locale "En_US"--and in Cshish shells (csh, tcsh)
279
280               setenv LC_ALL en_US.ISO8859-1
281
282       or if you have the "env" application you can do in any shell
283
284               env LC_ALL=en_US.ISO8859-1 perl ...
285
286       If you do not know what shell you have, consult your local helpdesk or
287       the equivalent.
288
289       Permanently fixing locale problems
290
291       The slower but superior fixes are when you may be able to yourself fix
292       the misconfiguration of your own environment variables.  The
293       mis(sing)configuration of the whole system's locales usually requires
294       the help of your friendly system administrator.
295
296       First, see earlier in this document about "Finding locales".  That
297       tells how to find which locales are really supported--and more impor‐
298       tantly, installed--on your system.  In our example error message, envi‐
299       ronment variables affecting the locale are listed in the order of
300       decreasing importance (and unset variables do not matter).  Therefore,
301       having LC_ALL set to "En_US" must have been the bad choice, as shown by
302       the error message.  First try fixing locale settings listed first.
303
304       Second, if using the listed commands you see something exactly (prefix
305       matches do not count and case usually counts) like "En_US" without the
306       quotes, then you should be okay because you are using a locale name
307       that should be installed and available in your system.  In this case,
308       see "Permanently fixing your system's locale configuration".
309
310       Permanently fixing your system's locale configuration
311
312       This is when you see something like:
313
314               perl: warning: Please check that your locale settings:
315                       LC_ALL = "En_US",
316                       LANG = (unset)
317                   are supported and installed on your system.
318
319       but then cannot see that "En_US" listed by the above-mentioned com‐
320       mands.  You may see things like "en_US.ISO8859-1", but that isn't the
321       same.  In this case, try running under a locale that you can list and
322       which somehow matches what you tried.  The rules for matching locale
323       names are a bit vague because standardization is weak in this area.
324       See again the "Finding locales" about general rules.
325
326       Fixing system locale configuration
327
328       Contact a system administrator (preferably your own) and report the
329       exact error message you get, and ask them to read this same documenta‐
330       tion you are now reading.  They should be able to check whether there
331       is something wrong with the locale configuration of the system.  The
332       "Finding locales" section is unfortunately a bit vague about the exact
333       commands and places because these things are not that standardized.
334
335       The localeconv function
336
337       The POSIX::localeconv() function allows you to get particulars of the
338       locale-dependent numeric formatting information specified by the cur‐
339       rent "LC_NUMERIC" and "LC_MONETARY" locales.  (If you just want the
340       name of the current locale for a particular category, use POSIX::setlo‐
341       cale() with a single parameter--see "The setlocale function".)
342
343               use POSIX qw(locale_h);
344
345               # Get a reference to a hash of locale-dependent info
346               $locale_values = localeconv();
347
348               # Output sorted list of the values
349               for (sort keys %$locale_values) {
350                   printf "%-20s = %s\n", $_, $locale_values->{$_}
351               }
352
353       localeconv() takes no arguments, and returns a reference to a hash.
354       The keys of this hash are variable names for formatting, such as "deci‐
355       mal_point" and "thousands_sep".  The values are the corresponding, er,
356       values.  See "localeconv" in POSIX for a longer example listing the
357       categories an implementation might be expected to provide; some provide
358       more and others fewer.  You don't need an explicit "use locale",
359       because localeconv() always observes the current locale.
360
361       Here's a simple-minded example program that rewrites its command-line
362       parameters as integers correctly formatted in the current locale:
363
364               # See comments in previous example
365               require 5.004;
366               use POSIX qw(locale_h);
367
368               # Get some of locale's numeric formatting parameters
369               my ($thousands_sep, $grouping) =
370                    @{localeconv()}{'thousands_sep', 'grouping'};
371
372               # Apply defaults if values are missing
373               $thousands_sep = ',' unless $thousands_sep;
374
375               # grouping and mon_grouping are packed lists
376               # of small integers (characters) telling the
377               # grouping (thousand_seps and mon_thousand_seps
378               # being the group dividers) of numbers and
379               # monetary quantities.  The integers' meanings:
380               # 255 means no more grouping, 0 means repeat
381               # the previous grouping, 1-254 means use that
382               # as the current grouping.  Grouping goes from
383               # right to left (low to high digits).  In the
384               # below we cheat slightly by never using anything
385               # else than the first grouping (whatever that is).
386               if ($grouping) {
387                   @grouping = unpack("C*", $grouping);
388               } else {
389                   @grouping = (3);
390               }
391
392               # Format command line params for current locale
393               for (@ARGV) {
394                   $_ = int;    # Chop non-integer part
395                   1 while
396                   s/(\d)(\d{$grouping[0]}($⎪$thousands_sep))/$1$thousands_sep$2/;
397                   print "$_";
398               }
399               print "\n";
400
401       I18N::Langinfo
402
403       Another interface for querying locale-dependent information is the
404       I18N::Langinfo::langinfo() function, available at least in UNIX-like
405       systems and VMS.
406
407       The following example will import the langinfo() function itself and
408       three constants to be used as arguments to langinfo(): a constant for
409       the abbreviated first day of the week (the numbering starts from Sunday
410       = 1) and two more constants for the affirmative and negative answers
411       for a yes/no question in the current locale.
412
413           use I18N::Langinfo qw(langinfo ABDAY_1 YESSTR NOSTR);
414
415           my ($abday_1, $yesstr, $nostr) = map { langinfo } qw(ABDAY_1 YESSTR NOSTR);
416
417           print "$abday_1? [$yesstr/$nostr] ";
418
419       In other words, in the "C" (or English) locale the above will probably
420       print something like:
421
422           Sun? [yes/no]
423
424       See I18N::Langinfo for more information.
425

LOCALE CATEGORIES

427       The following subsections describe basic locale categories.  Beyond
428       these, some combination categories allow manipulation of more than one
429       basic category at a time.  See "ENVIRONMENT" for a discussion of these.
430
431       Category LC_COLLATE: Collation
432
433       In the scope of "use locale", Perl looks to the "LC_COLLATE" environ‐
434       ment variable to determine the application's notions on collation
435       (ordering) of characters.  For example, 'b' follows 'a' in Latin alpha‐
436       bets, but where do 'a' and 'aa' belong?  And while 'color' follows
437       'chocolate' in English, what about in Spanish?
438
439       The following collations all make sense and you may meet any of them if
440       you "use locale".
441
442               A B C D E a b c d e
443               A a B b C c D d E e
444               a A b B c C d D e E
445               a b c d e A B C D E
446
447       Here is a code snippet to tell what "word" characters are in the cur‐
448       rent locale, in that locale's order:
449
450               use locale;
451               print +(sort grep /\w/, map { chr } 0..255), "\n";
452
453       Compare this with the characters that you see and their order if you
454       state explicitly that the locale should be ignored:
455
456               no locale;
457               print +(sort grep /\w/, map { chr } 0..255), "\n";
458
459       This machine-native collation (which is what you get unless
460       "use locale" has appeared earlier in the same block) must be used for
461       sorting raw binary data, whereas the locale-dependent collation of the
462       first example is useful for natural text.
463
464       As noted in "USING LOCALES", "cmp" compares according to the current
465       collation locale when "use locale" is in effect, but falls back to a
466       char-by-char comparison for strings that the locale says are equal. You
467       can use POSIX::strcoll() if you don't want this fall-back:
468
469               use POSIX qw(strcoll);
470               $equal_in_locale =
471                   !strcoll("space and case ignored", "SpaceAndCaseIgnored");
472
473       $equal_in_locale will be true if the collation locale specifies a dic‐
474       tionary-like ordering that ignores space characters completely and
475       which folds case.
476
477       If you have a single string that you want to check for "equality in
478       locale" against several others, you might think you could gain a little
479       efficiency by using POSIX::strxfrm() in conjunction with "eq":
480
481               use POSIX qw(strxfrm);
482               $xfrm_string = strxfrm("Mixed-case string");
483               print "locale collation ignores spaces\n"
484                   if $xfrm_string eq strxfrm("Mixed-casestring");
485               print "locale collation ignores hyphens\n"
486                   if $xfrm_string eq strxfrm("Mixedcase string");
487               print "locale collation ignores case\n"
488                   if $xfrm_string eq strxfrm("mixed-case string");
489
490       strxfrm() takes a string and maps it into a transformed string for use
491       in char-by-char comparisons against other transformed strings during
492       collation.  "Under the hood", locale-affected Perl comparison operators
493       call strxfrm() for both operands, then do a char-by-char comparison of
494       the transformed strings.  By calling strxfrm() explicitly and using a
495       non locale-affected comparison, the example attempts to save a couple
496       of transformations.  But in fact, it doesn't save anything: Perl magic
497       (see "Magic Variables" in perlguts) creates the transformed version of
498       a string the first time it's needed in a comparison, then keeps this
499       version around in case it's needed again.  An example rewritten the
500       easy way with "cmp" runs just about as fast.  It also copes with null
501       characters embedded in strings; if you call strxfrm() directly, it
502       treats the first null it finds as a terminator.  don't expect the
503       transformed strings it produces to be portable across systems--or even
504       from one revision of your operating system to the next.  In short,
505       don't call strxfrm() directly: let Perl do it for you.
506
507       Note: "use locale" isn't shown in some of these examples because it
508       isn't needed: strcoll() and strxfrm() exist only to generate locale-
509       dependent results, and so always obey the current "LC_COLLATE" locale.
510
511       Category LC_CTYPE: Character Types
512
513       In the scope of "use locale", Perl obeys the "LC_CTYPE" locale setting.
514       This controls the application's notion of which characters are alpha‐
515       betic.  This affects Perl's "\w" regular expression metanotation, which
516       stands for alphanumeric characters--that is, alphabetic, numeric, and
517       including other special characters such as the underscore or hyphen.
518       (Consult perlre for more information about regular expressions.)
519       Thanks to "LC_CTYPE", depending on your locale setting, characters like
520       'ae', 'd`', 'ss', and 'o' may be understood as "\w" characters.
521
522       The "LC_CTYPE" locale also provides the map used in transliterating
523       characters between lower and uppercase.  This affects the case-mapping
524       functions--lc(), lcfirst, uc(), and ucfirst(); case-mapping interpola‐
525       tion with "\l", "\L", "\u", or "\U" in double-quoted strings and "s///"
526       substitutions; and case-independent regular expression pattern matching
527       using the "i" modifier.
528
529       Finally, "LC_CTYPE" affects the POSIX character-class test func‐
530       tions--isalpha(), islower(), and so on.  For example, if you move from
531       the "C" locale to a 7-bit Scandinavian one, you may find--possibly to
532       your surprise--that "⎪" moves from the ispunct() class to isalpha().
533
534       Note: A broken or malicious "LC_CTYPE" locale definition may result in
535       clearly ineligible characters being considered to be alphanumeric by
536       your application.  For strict matching of (mundane) letters and dig‐
537       its--for example, in command strings--locale-aware applications should
538       use "\w" inside a "no locale" block.  See "SECURITY".
539
540       Category LC_NUMERIC: Numeric Formatting
541
542       In the scope of "use locale", Perl obeys the "LC_NUMERIC" locale infor‐
543       mation, which controls an application's idea of how numbers should be
544       formatted for human readability by the printf(), sprintf(), and write()
545       functions.  String-to-numeric conversion by the POSIX::strtod() func‐
546       tion is also affected.  In most implementations the only effect is to
547       change the character used for the decimal point--perhaps from '.'  to
548       ','.  These functions aren't aware of such niceties as thousands sepa‐
549       ration and so on.  (See "The localeconv function" if you care about
550       these things.)
551
552       Output produced by print() is also affected by the current locale: it
553       depends on whether "use locale" or "no locale" is in effect, and corre‐
554       sponds to what you'd get from printf() in the "C" locale.  The same is
555       true for Perl's internal conversions between numeric and string for‐
556       mats:
557
558               use POSIX qw(strtod);
559               use locale;
560
561               $n = 5/2;   # Assign numeric 2.5 to $n
562
563               $a = " $n"; # Locale-dependent conversion to string
564
565               print "half five is $n\n";       # Locale-dependent output
566
567               printf "half five is %g\n", $n;  # Locale-dependent output
568
569               print "DECIMAL POINT IS COMMA\n"
570                   if $n == (strtod("2,5"))[0]; # Locale-dependent conversion
571
572       See also I18N::Langinfo and "RADIXCHAR".
573
574       Category LC_MONETARY: Formatting of monetary amounts
575
576       The C standard defines the "LC_MONETARY" category, but no function that
577       is affected by its contents.  (Those with experience of standards com‐
578       mittees will recognize that the working group decided to punt on the
579       issue.)  Consequently, Perl takes no notice of it.  If you really want
580       to use "LC_MONETARY", you can query its contents--see "The localeconv
581       function"--and use the information that it returns in your applica‐
582       tion's own formatting of currency amounts.  However, you may well find
583       that the information, voluminous and complex though it may be, still
584       does not quite meet your requirements: currency formatting is a hard
585       nut to crack.
586
587       See also I18N::Langinfo and "CRNCYSTR".
588
589       LC_TIME
590
591       Output produced by POSIX::strftime(), which builds a formatted human-
592       readable date/time string, is affected by the current "LC_TIME" locale.
593       Thus, in a French locale, the output produced by the %B format element
594       (full month name) for the first month of the year would be "janvier".
595       Here's how to get a list of long month names in the current locale:
596
597               use POSIX qw(strftime);
598               for (0..11) {
599                   $long_month_name[$_] =
600                       strftime("%B", 0, 0, 0, 1, $_, 96);
601               }
602
603       Note: "use locale" isn't needed in this example: as a function that
604       exists only to generate locale-dependent results, strftime() always
605       obeys the current "LC_TIME" locale.
606
607       See also I18N::Langinfo and "ABDAY_1".."ABDAY_7", "DAY_1".."DAY_7",
608       "ABMON_1".."ABMON_12", and "ABMON_1".."ABMON_12".
609
610       Other categories
611
612       The remaining locale category, "LC_MESSAGES" (possibly supplemented by
613       others in particular implementations) is not currently used by
614       Perl--except possibly to affect the behavior of library functions
615       called by extensions outside the standard Perl distribution and by the
616       operating system and its utilities.  Note especially that the string
617       value of $! and the error messages given by external utilities may be
618       changed by "LC_MESSAGES".  If you want to have portable error codes,
619       use "%!".  See Errno.
620

SECURITY

622       Although the main discussion of Perl security issues can be found in
623       perlsec, a discussion of Perl's locale handling would be incomplete if
624       it did not draw your attention to locale-dependent security issues.
625       Locales--particularly on systems that allow unprivileged users to build
626       their own locales--are untrustworthy.  A malicious (or just plain bro‐
627       ken) locale can make a locale-aware application give unexpected
628       results.  Here are a few possibilities:
629
630       ·   Regular expression checks for safe file names or mail addresses
631           using "\w" may be spoofed by an "LC_CTYPE" locale that claims that
632           characters such as ">" and "⎪" are alphanumeric.
633
634       ·   String interpolation with case-mapping, as in, say, "$dest =
635           "C:\U$name.$ext"", may produce dangerous results if a bogus
636           LC_CTYPE case-mapping table is in effect.
637
638       ·   A sneaky "LC_COLLATE" locale could result in the names of students
639           with "D" grades appearing ahead of those with "A"s.
640
641       ·   An application that takes the trouble to use information in
642           "LC_MONETARY" may format debits as if they were credits and vice
643           versa if that locale has been subverted.  Or it might make payments
644           in US dollars instead of Hong Kong dollars.
645
646       ·   The date and day names in dates formatted by strftime() could be
647           manipulated to advantage by a malicious user able to subvert the
648           "LC_DATE" locale.  ("Look--it says I wasn't in the building on Sun‐
649           day.")
650
651       Such dangers are not peculiar to the locale system: any aspect of an
652       application's environment which may be modified maliciously presents
653       similar challenges.  Similarly, they are not specific to Perl: any pro‐
654       gramming language that allows you to write programs that take account
655       of their environment exposes you to these issues.
656
657       Perl cannot protect you from all possibilities shown in the exam‐
658       ples--there is no substitute for your own vigilance--but, when "use
659       locale" is in effect, Perl uses the tainting mechanism (see perlsec) to
660       mark string results that become locale-dependent, and which may be
661       untrustworthy in consequence.  Here is a summary of the tainting behav‐
662       ior of operators and functions that may be affected by the locale:
663
664       ·   Comparison operators ("lt", "le", "ge", "gt" and "cmp"):
665
666           Scalar true/false (or less/equal/greater) result is never tainted.
667
668       ·   Case-mapping interpolation (with "\l", "\L", "\u" or "\U")
669
670           Result string containing interpolated material is tainted if "use
671           locale" is in effect.
672
673       ·   Matching operator ("m//"):
674
675           Scalar true/false result never tainted.
676
677           Subpatterns, either delivered as a list-context result or as $1
678           etc.  are tainted if "use locale" is in effect, and the subpattern
679           regular expression contains "\w" (to match an alphanumeric charac‐
680           ter), "\W" (non-alphanumeric character), "\s" (whitespace charac‐
681           ter), or "\S" (non whitespace character).  The matched-pattern
682           variable, $&, $` (pre-match), $' (post-match), and $+ (last match)
683           are also tainted if "use locale" is in effect and the regular
684           expression contains "\w", "\W", "\s", or "\S".
685
686       ·   Substitution operator ("s///"):
687
688           Has the same behavior as the match operator.  Also, the left oper‐
689           and of "=~" becomes tainted when "use locale" in effect if modified
690           as a result of a substitution based on a regular expression match
691           involving "\w", "\W", "\s", or "\S"; or of case-mapping with "\l",
692           "\L","\u" or "\U".
693
694       ·   Output formatting functions (printf() and write()):
695
696           Results are never tainted because otherwise even output from print,
697           for example "print(1/7)", should be tainted if "use locale" is in
698           effect.
699
700       ·   Case-mapping functions (lc(), lcfirst(), uc(), ucfirst()):
701
702           Results are tainted if "use locale" is in effect.
703
704       ·   POSIX locale-dependent functions (localeconv(), strcoll(), strf‐
705           time(), strxfrm()):
706
707           Results are never tainted.
708
709       ·   POSIX character class tests (isalnum(), isalpha(), isdigit(),
710           isgraph(), islower(), isprint(), ispunct(), isspace(), isupper(),
711           isxdigit()):
712
713           True/false results are never tainted.
714
715       Three examples illustrate locale-dependent tainting.  The first pro‐
716       gram, which ignores its locale, won't run: a value taken directly from
717       the command line may not be used to name an output file when taint
718       checks are enabled.
719
720               #/usr/local/bin/perl -T
721               # Run with taint checking
722
723               # Command line sanity check omitted...
724               $tainted_output_file = shift;
725
726               open(F, ">$tainted_output_file")
727                   or warn "Open of $untainted_output_file failed: $!\n";
728
729       The program can be made to run by "laundering" the tainted value
730       through a regular expression: the second example--which still ignores
731       locale information--runs, creating the file named on its command line
732       if it can.
733
734               #/usr/local/bin/perl -T
735
736               $tainted_output_file = shift;
737               $tainted_output_file =~ m%[\w/]+%;
738               $untainted_output_file = $&;
739
740               open(F, ">$untainted_output_file")
741                   or warn "Open of $untainted_output_file failed: $!\n";
742
743       Compare this with a similar but locale-aware program:
744
745               #/usr/local/bin/perl -T
746
747               $tainted_output_file = shift;
748               use locale;
749               $tainted_output_file =~ m%[\w/]+%;
750               $localized_output_file = $&;
751
752               open(F, ">$localized_output_file")
753                   or warn "Open of $localized_output_file failed: $!\n";
754
755       This third program fails to run because $& is tainted: it is the result
756       of a match involving "\w" while "use locale" is in effect.
757

ENVIRONMENT

759       PERL_BADLANG
760                   A string that can suppress Perl's warning about failed
761                   locale settings at startup.  Failure can occur if the
762                   locale support in the operating system is lacking (broken)
763                   in some way--or if you mistyped the name of a locale when
764                   you set up your environment.  If this environment variable
765                   is absent, or has a value that does not evaluate to integer
766                   zero--that is, "0" or ""-- Perl will complain about locale
767                   setting failures.
768
769                   NOTE: PERL_BADLANG only gives you a way to hide the warning
770                   message.  The message tells about some problem in your sys‐
771                   tem's locale support, and you should investigate what the
772                   problem is.
773
774       The following environment variables are not specific to Perl: They are
775       part of the standardized (ISO C, XPG4, POSIX 1.c) setlocale() method
776       for controlling an application's opinion on data.
777
778       LC_ALL      "LC_ALL" is the "override-all" locale environment variable.
779                   If set, it overrides all the rest of the locale environment
780                   variables.
781
782       LANGUAGE    NOTE: "LANGUAGE" is a GNU extension, it affects you only if
783                   you are using the GNU libc.  This is the case if you are
784                   using e.g. Linux.  If you are using "commercial" UNIXes you
785                   are most probably not using GNU libc and you can ignore
786                   "LANGUAGE".
787
788                   However, in the case you are using "LANGUAGE": it affects
789                   the language of informational, warning, and error messages
790                   output by commands (in other words, it's like "LC_MES‐
791                   SAGES") but it has higher priority than LC_ALL.  Moreover,
792                   it's not a single value but instead a "path" (":"-separated
793                   list) of languages (not locales).  See the GNU "gettext"
794                   library documentation for more information.
795
796       LC_CTYPE    In the absence of "LC_ALL", "LC_CTYPE" chooses the charac‐
797                   ter type locale.  In the absence of both "LC_ALL" and
798                   "LC_CTYPE", "LANG" chooses the character type locale.
799
800       LC_COLLATE  In the absence of "LC_ALL", "LC_COLLATE" chooses the colla‐
801                   tion (sorting) locale.  In the absence of both "LC_ALL" and
802                   "LC_COLLATE", "LANG" chooses the collation locale.
803
804       LC_MONETARY In the absence of "LC_ALL", "LC_MONETARY" chooses the mone‐
805                   tary formatting locale.  In the absence of both "LC_ALL"
806                   and "LC_MONETARY", "LANG" chooses the monetary formatting
807                   locale.
808
809       LC_NUMERIC  In the absence of "LC_ALL", "LC_NUMERIC" chooses the
810                   numeric format locale.  In the absence of both "LC_ALL" and
811                   "LC_NUMERIC", "LANG" chooses the numeric format.
812
813       LC_TIME     In the absence of "LC_ALL", "LC_TIME" chooses the date and
814                   time formatting locale.  In the absence of both "LC_ALL"
815                   and "LC_TIME", "LANG" chooses the date and time formatting
816                   locale.
817
818       LANG        "LANG" is the "catch-all" locale environment variable. If
819                   it is set, it is used as the last resort after the overall
820                   "LC_ALL" and the category-specific "LC_...".
821

NOTES

823       Backward compatibility
824
825       Versions of Perl prior to 5.004 mostly ignored locale information, gen‐
826       erally behaving as if something similar to the "C" locale were always
827       in force, even if the program environment suggested otherwise (see "The
828       setlocale function").  By default, Perl still behaves this way for
829       backward compatibility.  If you want a Perl application to pay atten‐
830       tion to locale information, you must use the "use locale" pragma (see
831       "The use locale pragma") to instruct it to do so.
832
833       Versions of Perl from 5.002 to 5.003 did use the "LC_CTYPE" information
834       if available; that is, "\w" did understand what were the letters
835       according to the locale environment variables.  The problem was that
836       the user had no control over the feature: if the C library supported
837       locales, Perl used them.
838
839       I18N:Collate obsolete
840
841       In versions of Perl prior to 5.004, per-locale collation was possible
842       using the "I18N::Collate" library module.  This module is now mildly
843       obsolete and should be avoided in new applications.  The "LC_COLLATE"
844       functionality is now integrated into the Perl core language: One can
845       use locale-specific scalar data completely normally with "use locale",
846       so there is no longer any need to juggle with the scalar references of
847       "I18N::Collate".
848
849       Sort speed and memory use impacts
850
851       Comparing and sorting by locale is usually slower than the default
852       sorting; slow-downs of two to four times have been observed.  It will
853       also consume more memory: once a Perl scalar variable has participated
854       in any string comparison or sorting operation obeying the locale colla‐
855       tion rules, it will take 3-15 times more memory than before.  (The
856       exact multiplier depends on the string's contents, the operating system
857       and the locale.) These downsides are dictated more by the operating
858       system's implementation of the locale system than by Perl.
859
860       write() and LC_NUMERIC
861
862       Formats are the only part of Perl that unconditionally use information
863       from a program's locale; if a program's environment specifies an
864       LC_NUMERIC locale, it is always used to specify the decimal point char‐
865       acter in formatted output.  Formatted output cannot be controlled by
866       "use locale" because the pragma is tied to the block structure of the
867       program, and, for historical reasons, formats exist outside that block
868       structure.
869
870       Freely available locale definitions
871
872       There is a large collection of locale definitions at
873       ftp://dkuug.dk/i18n/WG15-collection .  You should be aware that it is
874       unsupported, and is not claimed to be fit for any purpose.  If your
875       system allows installation of arbitrary locales, you may find the defi‐
876       nitions useful as they are, or as a basis for the development of your
877       own locales.
878
879       I18n and l10n
880
881       "Internationalization" is often abbreviated as i18n because its first
882       and last letters are separated by eighteen others.  (You may guess why
883       the internalin ... internaliti ... i18n tends to get abbreviated.)  In
884       the same way, "localization" is often abbreviated to l10n.
885
886       An imperfect standard
887
888       Internationalization, as defined in the C and POSIX standards, can be
889       criticized as incomplete, ungainly, and having too large a granularity.
890       (Locales apply to a whole process, when it would arguably be more use‐
891       ful to have them apply to a single thread, window group, or whatever.)
892       They also have a tendency, like standards groups, to divide the world
893       into nations, when we all know that the world can equally well be
894       divided into bankers, bikers, gamers, and so on.  But, for now, it's
895       the only standard we've got.  This may be construed as a bug.
896

Unicode and UTF-8

898       The support of Unicode is new starting from Perl version 5.6, and more
899       fully implemented in the version 5.8.  See perluniintro and perlunicode
900       for more details.
901
902       Usually locale settings and Unicode do not affect each other, but there
903       are exceptions, see "Locales" in perlunicode for examples.
904

BUGS

906       Broken systems
907
908       In certain systems, the operating system's locale support is broken and
909       cannot be fixed or used by Perl.  Such deficiencies can and will result
910       in mysterious hangs and/or Perl core dumps when the "use locale" is in
911       effect.  When confronted with such a system, please report in excruci‐
912       ating detail to <perlbug@perl.org>, and complain to your vendor: bug
913       fixes may exist for these problems in your operating system.  Sometimes
914       such bug fixes are called an operating system upgrade.
915

SEE ALSO

917       I18N::Langinfo, perluniintro, perlunicode, open, "isalnum" in POSIX,
918       "isalpha" in POSIX, "isdigit" in POSIX, "isgraph" in POSIX, "islower"
919       in POSIX, "isprint" in POSIX, "ispunct" in POSIX, "isspace" in POSIX,
920       "isupper" in POSIX, "isxdigit" in POSIX, "localeconv" in POSIX, "setlo‐
921       cale" in POSIX, "strcoll" in POSIX, "strftime" in POSIX, "strtod" in
922       POSIX, "strxfrm" in POSIX.
923

HISTORY

925       Jarkko Hietaniemi's original perli18n.pod heavily hacked by Dominic
926       Dunlop, assisted by the perl5-porters.  Prose worked over a bit by Tom
927       Christiansen.
928
929       Last update: Thu Jun 11 08:44:13 MDT 1998
930
931
932
933perl v5.8.8                       2006-01-07                     PERLLOCALE(1)
Impressum