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