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