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