Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

980 lines
40 KiB

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