1=encoding utf8 2 3=head1 NAME 4 5perllocale - Perl locale handling (internationalization and localization) 6 7=head1 DESCRIPTION 8 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 (as long as they 12don't need the cents C<E<162>> symbol, as it is not in ASCII)). But it 13doesn't work so well even for other English speakers, who may use 14different currencies, such as the pound sterling C<E<163>> (as the 15symbol for that currency is also not in ASCII); and it's hopelessly 16inadequate for many of the thousands of the world's other languages. 17 18To address these deficiencies, the concept of locales was invented 19(formally the ISO C, XPG4, POSIX 1.c "locale system"). These allow for 20users to interface with their computer more according to their preferences. 21Applications were and are being written that use the locale mechanism. 22The process of making such an application take account of its users' 23preferences in these kinds of matters is called B<internationalization> 24(often abbreviated as B<i18n>); telling such an application about a 25particular set of preferences is known as B<localization> (B<l10n>). 26 27Perl has been extended to support certain types of locales available in 28the locale system. This is controlled per application by using one 29pragma, one function call, and several environment variables. 30 31Perl supports single-byte locales that are supersets of ASCII, such as 32the ISO 8859 ones, and one multi-byte-type locale, UTF-8 ones, described 33in the next paragraph. Perl doesn't support any other multi-byte 34locales, such as the ones for East Asian languages. 35 36Unfortunately, there are quite a few deficiencies with the design (and 37often, the implementations) of locales. Unicode was invented (see 38L<perlunitut> for an introduction to that) in part to address these 39design deficiencies, and nowadays, there is a series of "UTF-8 40locales", based on Unicode. These are locales whose character set is 41Unicode, encoded in UTF-8. Starting in v5.20, Perl fully supports 42UTF-8 locales, except for sorting and string comparisons like C<lt> and 43C<ge>. Starting in v5.26, Perl can handle these reasonably as well, 44depending on the platform's implementation. However, for earlier 45releases or for better control, use L<Unicode::Collate>. 46 47There are actually two slightly different types of UTF-8 locales: one 48for Turkic languages and one for everything else. Starting in Perl 49v5.30, Perl detects UTF-8 Turkic locales by their behaviour, and 50seamlessly handles both types; previously only the non-Turkic one was 51supported. The name of the locale is ignored; if your system has a 52C<tr_TR.UTF-8> locale and it doesn't behave like a Turkic locale, perl 53will treat it like a non-Turkic locale. 54 55Perl continues to support the old non UTF-8 locales as well. There are 56currently no UTF-8 locales for EBCDIC platforms. 57 58The perl interpreter is a C language program. At least stub locale 59support is required by the C language specification. So any instance of 60perl automatically has this. Later, the POSIX standard added more 61capabilities beyond the ones required by C. Perl supports these on the 62platforms where they are available. And Unicode supports a database of 63more types of information than the basic locale systems have. This 64database is called C<CLDR>, the "Common Locale Data Repository", 65L<http://cldr.unicode.org/>. There are various CPAN modules that 66provides access to this XML-encoded data, such as L<Locale::CLDR>, 67L<CLDR::Number>, and L<DateTime::Format::CLDR>. 68 69=head1 WHAT IS A LOCALE 70 71A locale is a set of data that describes various aspects of how various 72communities in the world categorize their world. These categories are 73broken down into the following types (some of which include a brief 74note here): 75 76=over 77 78=item Category C<LC_NUMERIC>: Numeric formatting 79 80This indicates how numbers should be formatted for human readability, 81for example the character used as the decimal point. 82 83=item Category C<LC_MONETARY>: Formatting of monetary amounts 84 85Z<> 86 87=item Category C<LC_TIME>: Date/Time formatting 88 89Z<> 90 91=item Category C<LC_COLLATE>: Collation 92 93This indicates the ordering of letters for comparison and sorting. 94In Latin alphabets, for example, "b", generally follows "a". 95 96=item Category C<LC_CTYPE>: Character Types 97 98This indicates, for example if a character is an uppercase letter. 99 100=item Category C<LC_MESSAGES>: Error and other messages 101 102This is a POSIX extension beyond the basic C language required 103categories. On Windows and other non-POSIX platforms, perl uses 104workarounds to simulate it. 105 106=item Category C<LC_TIME>: Date/Time formatting 107 108Z<> 109 110=item Category C<LC_ALL> 111 112This is not an actual category, but a convenience short-hand to refer to 113all of the actual ones. 114 115=item Other categories 116 117Some platforms have other categories, dealing with such things as 118measurement units and paper sizes. None of these are used directly by 119Perl, but outside operations that Perl interacts with may use 120these. See L</Not within the scope of "use locale"> below. 121 122=back 123 124More details on the categories used by Perl are given below in L</LOCALE 125CATEGORIES>. 126 127Together, these categories go a long way towards being able to customize 128a single program to run in many different locations. And adding Unicode 129CLDR goes further. But there are deficiencies, so keep reading. 130 131=head1 PREPARING TO USE LOCALES 132 133Perl itself (outside the L<POSIX> module) will not use locales unless 134specifically requested to (but 135again note that Perl may interact with code that does use them). Even 136if there is such a request, B<all> of the following must be true 137for it to work properly: 138 139=over 4 140 141=item * 142 143B<Perl must believe that the locale system is supported>. If it does, 144C<perl -V:d_setlocale> will say that the value for C<d_setlocale> is 145C<define>. 146 147=item * 148 149B<Definitions for the locales that you use must be installed>. All 150platforms that perl runs on are required to support at least one locale, 151named "C", which is essentially ASCII, and typical American preferences. 152 153Most platforms allow for additional locales, but these must be 154specifically installed. You, or your system administrator, must make 155sure that any locales you want are installed. The available locales, 156the location in which they are kept, and the manner in which they are 157installed all vary from system to system. Some systems provide only a 158few, hard-wired locales and do not allow more to be added. Others allow 159you to add "canned" locales provided by the system supplier. Still 160others allow you or the system administrator to define and add arbitrary 161locales. (You may have to ask your supplier to provide canned locales 162that are not delivered with your operating system.) Read your system 163documentation for further illumination. 164 165=back 166 167If you want a Perl application to process and present your data 168according to a particular locale, the application code should include 169the S<C<use locale>> pragma (see L</The "use locale" pragma>) where 170appropriate, and B<at least one> of the following must be true: 171 172=over 4 173 174=item 1 175 176B<The locale-determining environment variables (see L</"ENVIRONMENT">) 177must be correctly set up> at the time the application is started, either 178by yourself or by whomever set up your system account; or 179 180=item 2 181 182B<The application must set its own locale> using the method described in 183L</The setlocale function>. 184 185=back 186 187=head1 USING LOCALES 188 189=head2 The C<"use locale"> pragma 190 191By default, Perl itself (outside the L<POSIX> module) 192ignores the current locale. The S<C<use locale>> 193pragma tells Perl to use the current locale for some operations. 194Starting in v5.16, there are optional parameters to this pragma, 195described below, which restrict which operations are affected by it. 196 197Starting in Perl 5.28, this pragma may be used in 198L<multi-threaded|threads> applications on systems that have thread-safe 199locale ability. Some caveats apply, see L</Multi-threaded> below. On 200systems without this capability, or in earlier Perls, do NOT use this 201pragma in scripts that have multiple L<threads|threads> active. The 202locale in these cases is not local to a single thread. Another thread 203may change the locale at any time, which could cause at a minimum that a 204given thread is operating in a locale it isn't expecting to be in. On 205some platforms, segfaults can also occur. The locale change need not be 206explicit; some operations cause perl itself to change the locale. You 207are vulnerable simply by having done a S<C<"use locale">>. 208 209The current locale is set at execution time by 210L<setlocale()|/The setlocale function> described below. If that function 211hasn't yet been called in the course of the program's execution, the 212current locale is that which was determined by the L</"ENVIRONMENT"> in 213effect at the start of the program. 214If there is no valid environment, the current locale is whatever the 215system default has been set to. On POSIX systems, it is likely, but 216not necessarily, the "C" locale. On Windows, the default is set via the 217computer's S<C<Control Panel-E<gt>Regional and Language Options>> (or its 218current equivalent). 219 220The operations that are affected by locale are: 221 222=over 4 223 224=item B<Not within the scope of C<"use locale">> 225 226Only certain operations (all originating outside Perl) should be 227affected, as follows: 228 229=over 4 230 231=item * 232 233The current locale is used when going outside of Perl with 234operations like L<system()|perlfunc/system LIST> or 235L<qxE<sol>E<sol>|perlop/qxE<sol>STRINGE<sol>>, if those operations are 236locale-sensitive. 237 238=item * 239 240Also Perl gives access to various C library functions through the 241L<POSIX> module. Some of those functions are always affected by the 242current locale. For example, C<POSIX::strftime()> uses C<LC_TIME>; 243C<POSIX::strtod()> uses C<LC_NUMERIC>; C<POSIX::strcoll()> and 244C<POSIX::strxfrm()> use C<LC_COLLATE>. All such functions 245will behave according to the current underlying locale, even if that 246locale isn't exposed to Perl space. 247 248This applies as well to L<I18N::Langinfo>. 249 250=item * 251 252XS modules for all categories but C<LC_NUMERIC> get the underlying 253locale, and hence any C library functions they call will use that 254underlying locale. For more discussion, see 255L<perlclib/Dealing with locales>. 256 257=back 258 259Note that all C programs (including the perl interpreter, which is 260written in C) always have an underlying locale. That locale is the "C" 261locale unless changed by a call to L<setlocale()|/The setlocale 262function>. When Perl starts up, it changes the underlying locale to the 263one which is indicated by the L</ENVIRONMENT>. When using the L<POSIX> 264module or writing XS code, it is important to keep in mind that the 265underlying locale may be something other than "C", even if the program 266hasn't explicitly changed it. 267 268Z<> 269 270=item B<Lingering effects of C<S<use locale>>> 271 272Certain Perl operations that are set-up within the scope of a 273C<use locale> retain that effect even outside the scope. 274These include: 275 276=over 4 277 278=item * 279 280The output format of a L<write()|perlfunc/write> is determined by an 281earlier format declaration (L<perlfunc/format>), so whether or not the 282output is affected by locale is determined by if the C<format()> is 283within the scope of a C<use locale>, not whether the C<write()> 284is. 285 286=item * 287 288Regular expression patterns can be compiled using 289L<qrE<sol>E<sol>|perlop/qrE<sol>STRINGE<sol>msixpodualn> with actual 290matching deferred to later. Again, it is whether or not the compilation 291was done within the scope of C<use locale> that determines the match 292behavior, not if the matches are done within such a scope or not. 293 294=back 295 296Z<> 297 298=item B<Under C<"use locale";>> 299 300=over 4 301 302=item * 303 304All the above operations 305 306=item * 307 308B<Format declarations> (L<perlfunc/format>) and hence any subsequent 309C<write()>s use C<LC_NUMERIC>. 310 311=item * 312 313B<stringification and output> use C<LC_NUMERIC>. 314These include the results of 315C<print()>, 316C<printf()>, 317C<say()>, 318and 319C<sprintf()>. 320 321=item * 322 323B<The comparison operators> (C<lt>, C<le>, C<cmp>, C<ge>, and C<gt>) use 324C<LC_COLLATE>. C<sort()> is also affected if used without an 325explicit comparison function, because it uses C<cmp> by default. 326 327B<Note:> C<eq> and C<ne> are unaffected by locale: they always 328perform a char-by-char comparison of their scalar operands. What's 329more, if C<cmp> finds that its operands are equal according to the 330collation sequence specified by the current locale, it goes on to 331perform a char-by-char comparison, and only returns I<0> (equal) if the 332operands are char-for-char identical. If you really want to know whether 333two strings--which C<eq> and C<cmp> may consider different--are equal 334as far as collation in the locale is concerned, see the discussion in 335L</Category C<LC_COLLATE>: Collation>. 336 337=item * 338 339B<Regular expressions and case-modification functions> (C<uc()>, C<lc()>, 340C<ucfirst()>, and C<lcfirst()>) use C<LC_CTYPE> 341 342=item * 343 344B<The variables L<C<$!>|perlvar/$ERRNO>> (and its synonyms C<$ERRNO> and 345C<$OS_ERROR>) B<and> L<C<$^E>|perlvar/$EXTENDED_OS_ERROR>> (and its synonym 346C<$EXTENDED_OS_ERROR>) when used as strings use C<LC_MESSAGES> On 347platforms that lack this category C<LC_CTYPE> is used instead. 348 349=back 350 351=back 352 353The default behavior is restored with the S<C<no locale>> pragma, or 354upon reaching the end of the block enclosing C<use locale>. 355Note that C<use locale> calls may be 356nested, and that what is in effect within an inner scope will revert to 357the outer scope's rules at the end of the inner scope. 358 359The string result of any operation that uses locale 360information is tainted (if your perl supports taint checking), 361as it is possible for a locale to be untrustworthy. 362See L</"SECURITY">. 363 364Starting in Perl v5.16 in a very limited way, and more generally in 365v5.22, you can restrict which category or categories are enabled by this 366particular instance of the pragma by adding parameters to it. (This 367capability was to enable you to write code to work around deficiencies in 368perl's locale handling, which have since been corrected, so it is 369unlikely that new code will need to use it.) 370 371For example, 372 373 use locale qw(:ctype :numeric); 374 375enables locale awareness within its scope of only those operations 376(listed above) that are affected by C<LC_CTYPE> and C<LC_NUMERIC>. 377 378The possible categories are: C<:collate>, C<:ctype>, C<:messages>, 379C<:monetary>, C<:numeric>, C<:time>, and the pseudo category 380C<:characters> (described below). 381 382Thus you can say 383 384 use locale ':messages'; 385 386and only L<C<"$!">|perlvar/$ERRNO> and L<C<"$^E">|perlvar/$EXTENDED_OS_ERROR> 387will be locale aware. Everything else is unaffected. 388 389Since Perl doesn't currently do anything with the C<LC_MONETARY> 390category, specifying C<:monetary> does effectively nothing. Some 391systems have other categories, such as C<LC_PAPER>, but the perl core 392doesn't do anything with them, and there is no way to specify 393them in this pragma's arguments. 394 395You can also easily say to use all categories but one, by either, for 396example, 397 398 use locale ':!ctype'; 399 use locale ':not_ctype'; 400 401both of which mean to enable locale awareness of all categories but 402C<LC_CTYPE>. Only one category argument may be specified in a 403S<C<use locale>> if it is of the negated form. 404 405Prior to v5.22 only one form of the pragma with arguments is available: 406 407 use locale ':not_characters'; 408 409(and you have to say C<not_>; you can't use the bang C<!> form). This 410pseudo category is a shorthand for specifying both C<:collate> and 411C<:ctype>. Hence, in the negated form, it is nearly the same thing as 412saying 413 414 use locale qw(:messages :monetary :numeric :time); 415 416We use the term "nearly", because C<:not_characters> also turns on 417S<C<use feature 'unicode_strings'>> within its scope. This form is 418less useful in v5.20 and later, and is described fully in 419L</Unicode and UTF-8>, but briefly, it tells Perl to not use the 420character portions of the locale definition, that is the C<LC_CTYPE> and 421C<LC_COLLATE> categories. Instead it will use the native character set 422(extended by Unicode). When using this parameter, you are responsible 423for getting the external character set translated into the 424native/Unicode one (which it already will be if it is one of the 425increasingly popular UTF-8 locales). There are convenient ways of doing 426this, as described in L</Unicode and UTF-8>. 427 428=head2 The setlocale function 429 430WARNING! Prior to Perl 5.28 or on a system that does not support 431thread-safe locale operations, do NOT use this function in a 432L<thread|threads>. The locale will change in all other threads at the 433same time, and should your thread get paused by the operating system, 434and another started, that thread will not have the locale it is 435expecting. On some platforms, there can be a race leading to segfaults 436if two threads call this function nearly simultaneously. This warning 437does not apply on unthreaded builds, or on perls where 438C<${^SAFE_LOCALES}> exists and is non-zero; namely Perl 5.28 and later 439unthreaded or compiled to be locale-thread-safe. On z/OS systems, this 440function becomes a no-op once any thread is started. Thus, on that 441system, you can set up the locale before creating any threads, and that 442locale will be the one in effect for the entire program. 443 444Otherwise, you can switch locales as often as you wish at run time with 445the C<POSIX::setlocale()> function: 446 447 # Import locale-handling tool set from POSIX module. 448 # This example uses: setlocale -- the function call 449 # LC_CTYPE -- explained below 450 # (Showing the testing for success/failure of operations is 451 # omitted in these examples to avoid distracting from the main 452 # point) 453 454 use POSIX qw(locale_h); 455 use locale; 456 my $old_locale; 457 458 # query and save the old locale 459 $old_locale = setlocale(LC_CTYPE); 460 461 setlocale(LC_CTYPE, "fr_CA.ISO8859-1"); 462 # LC_CTYPE now in locale "French, Canada, codeset ISO 8859-1" 463 464 setlocale(LC_CTYPE, ""); 465 # LC_CTYPE now reset to the default defined by the 466 # LC_ALL/LC_CTYPE/LANG environment variables, or to the system 467 # default. See below for documentation. 468 469 # restore the old locale 470 setlocale(LC_CTYPE, $old_locale); 471 472The first argument of C<setlocale()> gives the B<category>, the second the 473B<locale>. The category tells in what aspect of data processing you 474want to apply locale-specific rules. Category names are discussed in 475L</LOCALE CATEGORIES> and L</"ENVIRONMENT">. The locale is the name of a 476collection of customization information corresponding to a particular 477combination of language, country or territory, and codeset. Read on for 478hints on the naming of locales: not all systems name locales as in the 479example. 480 481If no second argument is provided and the category is something other 482than C<LC_ALL>, the function returns a string naming the current locale 483for the category. You can use this value as the second argument in a 484subsequent call to C<setlocale()>, B<but> on some platforms the string 485is opaque, not something that most people would be able to decipher as 486to what locale it means. 487 488If no second argument is provided and the category is C<LC_ALL>, the 489result is implementation-dependent. It may be a string of 490concatenated locale names (separator also implementation-dependent) 491or a single locale name. Please consult your L<setlocale(3)> man page for 492details. 493 494If a second argument is given and it corresponds to a valid locale, 495the locale for the category is set to that value, and the function 496returns the now-current locale value. You can then use this in yet 497another call to C<setlocale()>. (In some implementations, the return 498value may sometimes differ from the value you gave as the second 499argument--think of it as an alias for the value you gave.) 500 501As the example shows, if the second argument is an empty string, the 502category's locale is returned to the default specified by the 503corresponding environment variables. Generally, this results in a 504return to the default that was in force when Perl started up: changes 505to the environment made by the application after startup may or may not 506be noticed, depending on your system's C library. 507 508Note that when a form of C<use locale> that doesn't include all 509categories is specified, Perl ignores the excluded categories. 510 511If C<setlocale()> fails for some reason (for example, an attempt to set 512to a locale unknown to the system), the locale for the category is not 513changed, and the function returns C<undef>. 514 515Starting in Perl 5.28, on multi-threaded perls compiled on systems that 516implement POSIX 2008 thread-safe locale operations, this function 517doesn't actually call the system C<setlocale>. Instead those 518thread-safe operations are used to emulate the C<setlocale> function, 519but in a thread-safe manner. 520 521You can force the thread-safe locale operations to always be used (if 522available) by recompiling perl with 523 524 -Accflags='-DUSE_THREAD_SAFE_LOCALE' 525 526added to your call to F<Configure>. 527 528For further information about the categories, consult L<setlocale(3)>. 529 530=head2 Multi-threaded operation 531 532Beginning in Perl 5.28, multi-threaded locale operation is supported on 533systems that implement either the POSIX 2008 or Windows-specific 534thread-safe locale operations. Many modern systems, such as various 535Unix variants do have this. Others, such as most *BSD-derived variants, 536including Darwin, claim to have it, but are buggy as of May 2024, so 537Perl avoids their use. 538 539You can tell if using locales is safe on your system by looking at the 540read-only variable C<${^SAFE_LOCALES}>. The value is 1 if the 541perl is not threaded, or if it is using thread-safe locale operations. 542 543Thread-safe operations are supported in Windows starting in Visual Studio 5442005, in cygwin, in MingW compiled to use UCRT (the Universal C Run Time 545library), and in systems compatible with POSIX 2008. 546C<${^SAFE_LOCALES}> will be 0 on threaded builds on platforms that Perl 547knows to have buggy implementations. 548 549Be aware that writing a multi-threaded application will not be portable 550to a platform which lacks the native thread-safe locale support. On 551systems that do have it, you automatically get this behavior for 552threaded perls, without having to do anything. If for some reason, you 553don't want to use this capability (perhaps the POSIX 2008 support turns 554out to be buggy on your system), you can manually compile Perl to use 555the old non-thread-safe implementation by passing the argument 556C<-Accflags='-DNO_THREAD_SAFE_LOCALE'> to F<Configure>. Except on 557Windows, this will continue to use certain of the POSIX 2008 functions 558in some situations. If these are buggy, you can pass the following to 559F<Configure> instead or additionally: 560C<-Accflags='-DNO_POSIX_2008_LOCALE'>. This will also keep the code 561from using thread-safe locales. 562C<${^SAFE_LOCALES}> will be 0 on systems that turn off the thread-safe 563operations. 564 565Normally on unthreaded builds, Perl uses the traditional C<setlocale()> 566to change the locale, and not the alternate POSIX 2008 thread-safe 567locale-changing functions. You can force the use of these on systems 568that have them by adding the C<-Accflags='-DUSE_THREAD_SAFE_LOCALE'> to 569F<Configure>. 570 571The initial program is started up using the locale specified from the 572environment, as currently, described in L</ENVIRONMENT>. All newly 573created threads start with C<LC_ALL> set to C<"C">. Each thread may 574use C<POSIX::setlocale()> to query or switch its locale at any time, 575without affecting any other thread. All locale-dependent operations 576automatically use their thread's locale. 577 578This should be completely transparent to any applications written 579entirely in Perl (minus a few rarely encountered caveats given in the 580L</Multi-threaded> section). Information for XS module writers is given 581in L<perlclib/Dealing with locales>. 582 583=head2 Finding locales 584 585For locales available in your system, consult also L<setlocale(3)> to 586see whether it leads to the list of available locales (search for the 587I<SEE ALSO> section). If that fails, try the following command lines: 588 589 locale -a 590 591 nlsinfo 592 593 ls /usr/lib/nls/loc 594 595 ls /usr/lib/locale 596 597 ls /usr/lib/nls 598 599 ls /usr/share/locale 600 601and see whether they list something resembling these 602 603 en_US.ISO8859-1 de_DE.ISO8859-1 ru_RU.ISO8859-5 604 en_US.iso88591 de_DE.iso88591 ru_RU.iso88595 605 en_US de_DE ru_RU 606 en de ru 607 english german russian 608 english.iso88591 german.iso88591 russian.iso88595 609 english.roman8 russian.koi8r 610 611Sadly, even though the calling interface for C<setlocale()> has been 612standardized, names of locales and the directories where the 613configuration resides have not been. The basic form of the name is 614I<language[_territory[.codeset]][@modifier]>. 615The I<language> and I<country> 616are usually from the standards B<ISO 3166> and B<ISO 639>, the 617two-letter abbreviations for the countries and the languages of the 618world, respectively. The I<codeset> part often mentions some B<ISO 6198859> character set, the Latin codesets. For example, C<ISO 8859-1> 620is the so-called "Western European codeset" that can be used to encode 621most Western European languages adequately. Again, there are several 622ways to write even the name of that one standard. Lamentably. 623I<modifier> is very individualized to the rest of the locale, naming 624some variant, such as a different currency symbol than the locale would 625normally contain. 626 627Two special locales are worth particular mention: "C" and "POSIX". 628Currently these are effectively the same locale: the difference is 629mainly that the first one is defined by the C standard, the second by 630the POSIX standard. They define the B<default locale> in which 631every program starts in the absence of locale information in its 632environment. (The I<default> default locale, if you will.) Its language 633is (American) English and its character codeset ASCII or, rarely, a 634superset thereof (such as the "DEC Multinational Character Set 635(DEC-MCS)"). B<Warning>. The C locale delivered by some vendors 636may not actually exactly match what the C standard calls for. So 637beware. 638 639B<NOTE>: Not all systems have the "POSIX" locale (not all systems are 640POSIX-conformant), so use "C" when you need explicitly to specify this 641default locale. 642 643=head2 LOCALE PROBLEMS 644 645You may encounter the following warning message at Perl startup: 646 647 perl: warning: Setting locale failed. 648 perl: warning: Please check that your locale settings: 649 LC_ALL = "En_US", 650 LANG = (unset) 651 are supported and installed on your system. 652 perl: warning: Falling back to the standard locale ("C"). 653 654This means that your locale settings had C<LC_ALL> set to "En_US" and 655LANG exists but has no value. Perl tried to believe you but could not. 656Instead, Perl gave up and fell back to the "C" locale, the default locale 657that is supposed to work no matter what. (On Windows, it first tries 658falling back to the system default locale.) This usually means your 659locale settings were wrong, they mention locales your system has never 660heard of, or the locale installation in your system has problems (for 661example, some system files are broken or missing). There are quick and 662temporary fixes to these problems, as well as more thorough and lasting 663fixes. 664 665=head3 Testing for broken locales 666 667If you are building Perl from source, the Perl test suite file 668F<lib/locale.t> can be used to test the locales on your system. 669Setting the environment variable C<PERL_DEBUG_FULL_TEST> to 1 670will cause it to output detailed results. For example, on Linux, you 671could say 672 673 PERL_DEBUG_FULL_TEST=1 ./perl -T -Ilib lib/locale.t > locale.log 2>&1 674 675Besides many other tests, it will test every locale it finds on your 676system to see if they conform to the POSIX standard. If any have 677errors, it will include a summary near the end of the output of which 678locales passed all its tests, and which failed, and why. 679 680=head3 Temporarily fixing locale problems 681 682The two quickest fixes are either to render Perl silent about any 683locale inconsistencies or to run Perl under the default locale "C". 684 685Perl's moaning about locale problems can be silenced by setting the 686environment variable C<PERL_BADLANG> to "0" or "". 687This method really just sweeps the problem under the carpet: you tell 688Perl to shut up even when Perl sees that something is wrong. Do not 689be surprised if later something locale-dependent misbehaves. 690 691Perl can be run under the "C" locale by setting the environment 692variable C<LC_ALL> to "C". This method is perhaps a bit more civilized 693than the C<PERL_BADLANG> approach, but setting C<LC_ALL> (or 694other locale variables) may affect other programs as well, not just 695Perl. In particular, external programs run from within Perl will see 696these changes. If you make the new settings permanent (read on), all 697programs you run see the changes. See L</"ENVIRONMENT"> for 698the full list of relevant environment variables and L</"USING LOCALES"> 699for their effects in Perl. Effects in other programs are 700easily deducible. For example, the variable C<LC_COLLATE> may well affect 701your B<sort> program (or whatever the program that arranges "records" 702alphabetically in your system is called). 703 704You can test out changing these variables temporarily, and if the 705new settings seem to help, put those settings into your shell startup 706files. Consult your local documentation for the exact details. For 707Bourne-like shells (B<sh>, B<ksh>, B<bash>, B<zsh>): 708 709 LC_ALL=en_US.ISO8859-1 710 export LC_ALL 711 712This assumes that we saw the locale "en_US.ISO8859-1" using the commands 713discussed above. We decided to try that instead of the above faulty 714locale "En_US". 715 716And in Csh-ish shells (B<csh>, B<tcsh>) 717 718 setenv LC_ALL en_US.ISO8859-1 719 720or if you have the "env" application you can do (in any shell) 721 722 env LC_ALL=en_US.ISO8859-1 perl ... 723 724If you do not know what shell you have, consult your local 725helpdesk or the equivalent. 726 727=head3 Permanently fixing locale problems 728 729The slower but superior fixes are when you may be able to yourself 730fix the misconfiguration of your own environment variables. The 731mis(sing)configuration of the whole system's locales usually requires 732the help of your system administrator. 733 734First, see earlier in this document about L</Finding locales>. That tells 735how to find which locales are really supported--and more importantly, 736installed--on your system. In our example error message, environment 737variables affecting the locale are listed in the order of decreasing 738importance (and unset variables do not matter). Therefore, having 739LC_ALL set to "En_US" must have been the bad choice, as shown by the 740error message. First try fixing locale settings listed first. 741 742Second, if using the listed commands you see something B<exactly> 743(prefix matches do not count and case usually counts) like "En_US" 744without the quotes, then you should be okay because you are using a 745locale name that should be installed and available in your system. 746In this case, see L</Permanently fixing your system's locale configuration>. 747 748=head3 Permanently fixing your system's locale configuration 749 750This is when you see something like: 751 752 perl: warning: Please check that your locale settings: 753 LC_ALL = "En_US", 754 LANG = (unset) 755 are supported and installed on your system. 756 757but then cannot see that "En_US" listed by the above-mentioned 758commands. You may see things like "en_US.ISO8859-1", but that isn't 759the same. In this case, try running under a locale 760that you can list and which somehow matches what you tried. The 761rules for matching locale names are a bit vague because 762standardization is weak in this area. See again the 763L</Finding locales> about general rules. 764 765=head3 Fixing system locale configuration 766 767Contact a system administrator (preferably your own) and report the exact 768error message you get, and ask them to read this same documentation you 769are now reading. They should be able to check whether there is something 770wrong with the locale configuration of the system. The L</Finding locales> 771section is unfortunately a bit vague about the exact commands and places 772because these things are not that standardized. 773 774=head2 The localeconv function 775 776The C<POSIX::localeconv()> function allows you to get particulars of the 777locale-dependent numeric formatting information specified by the current 778underlying C<LC_NUMERIC> and C<LC_MONETARY> locales (regardless of 779whether called from within the scope of C<S<use locale>> or not). (If 780you just want the name of 781the current locale for a particular category, use C<POSIX::setlocale()> 782with a single parameter--see L</The setlocale function>.) 783 784 use POSIX qw(locale_h); 785 786 # Get a reference to a hash of locale-dependent info 787 $locale_values = localeconv(); 788 789 # Output sorted list of the values 790 for (sort keys %$locale_values) { 791 printf "%-20s = %s\n", $_, $locale_values->{$_} 792 } 793 794C<localeconv()> takes no arguments, and returns B<a reference to> a hash. 795The keys of this hash are variable names for formatting, such as 796C<decimal_point> and C<thousands_sep>. The values are the 797corresponding, er, values. See L<POSIX/localeconv> for a longer 798example listing the categories an implementation might be expected to 799provide; some provide more and others fewer. You don't need an 800explicit C<use locale>, because C<localeconv()> always observes the 801current locale. 802 803Here's a simple-minded example program that rewrites its command-line 804parameters as integers correctly formatted in the current locale: 805 806 use POSIX qw(locale_h); 807 808 # Get some of locale's numeric formatting parameters 809 my ($thousands_sep, $grouping) = 810 @{localeconv()}{'thousands_sep', 'grouping'}; 811 812 # Apply defaults if values are missing 813 $thousands_sep = ',' unless $thousands_sep; 814 815 # grouping and mon_grouping are packed lists 816 # of small integers (characters) telling the 817 # grouping (thousand_seps and mon_thousand_seps 818 # being the group dividers) of numbers and 819 # monetary quantities. The integers' meanings: 820 # 255 means no more grouping, 0 means repeat 821 # the previous grouping, 1-254 means use that 822 # as the current grouping. Grouping goes from 823 # right to left (low to high digits). In the 824 # below we cheat slightly by never using anything 825 # else than the first grouping (whatever that is). 826 if ($grouping) { 827 @grouping = unpack("C*", $grouping); 828 } else { 829 @grouping = (3); 830 } 831 832 # Format command line params for current locale 833 for (@ARGV) { 834 $_ = int; # Chop non-integer part 835 1 while 836 s/(\d)(\d{$grouping[0]}($|$thousands_sep))/$1$thousands_sep$2/; 837 print "$_"; 838 } 839 print "\n"; 840 841Note that if the platform doesn't have C<LC_NUMERIC> and/or 842C<LC_MONETARY> available or enabled, the corresponding elements of the 843hash will be missing. 844 845=head2 I18N::Langinfo 846 847Another interface for querying locale-dependent information is the 848C<I18N::Langinfo::langinfo()> function. 849 850The following example will import the C<langinfo()> function itself and 851three constants to be used as arguments to C<langinfo()>: a constant for 852the abbreviated first day of the week (the numbering starts from 853Sunday = 1) and two more constants for the affirmative and negative 854answers for a yes/no question in the current locale. 855 856 use I18N::Langinfo qw(langinfo ABDAY_1 YESSTR NOSTR); 857 858 my ($abday_1, $yesstr, $nostr) 859 = map { langinfo } qw(ABDAY_1 YESSTR NOSTR); 860 861 print "$abday_1? [$yesstr/$nostr] "; 862 863In other words, in the "C" (or English) locale the above will probably 864print something like: 865 866 Sun? [yes/no] 867 868See L<I18N::Langinfo> for more information. 869 870=head1 LOCALE CATEGORIES 871 872The following subsections describe basic locale categories. Beyond these, 873some combination categories allow manipulation of more than one 874basic category at a time. See L</"ENVIRONMENT"> for a discussion of these. 875 876=head2 Category C<LC_COLLATE>: Collation: Text Comparisons and Sorting 877 878In the scope of a S<C<use locale>> form that includes collation, Perl 879looks to the C<LC_COLLATE> 880environment variable to determine the application's notions on collation 881(ordering) of characters. For example, "b" likely follows "a" in Latin 882alphabets, but where do "E<aacute>" and "E<aring>" belong? And while 883"color" follows "chocolate" in English, what about in traditional Spanish? 884 885The following collations all make sense and you may meet any of them 886if you C<"use locale">. 887 888 A B C D E a b c d e 889 A a B b C c D d E e 890 a A b B c C d D e E 891 a b c d e A B C D E 892 893Here is a code snippet to tell what "word" 894characters are in the current locale, in that locale's order: 895 896 use locale; 897 print +(sort grep /\w/, map { chr } 0..255), "\n"; 898 899Compare this with the characters that you see and their order if you 900state explicitly that the locale should be ignored: 901 902 no locale; 903 print +(sort grep /\w/, map { chr } 0..255), "\n"; 904 905This machine-native collation (which is what you get unless S<C<use 906locale>> has appeared earlier in the same block) must be used for 907sorting raw binary data, whereas the locale-dependent collation of the 908first example is useful for natural text. 909 910As noted in L</USING LOCALES>, C<cmp> compares according to the current 911collation locale when C<use locale> is in effect, but falls back to a 912char-by-char comparison for strings that the locale says are equal. You 913can use C<POSIX::strcoll()> if you don't want this fall-back: 914 915 use POSIX qw(strcoll); 916 $equal_in_locale = 917 !strcoll("space and case ignored", "SpaceAndCaseIgnored"); 918 919C<$equal_in_locale> will be true if the collation locale specifies a 920dictionary-like ordering that ignores space characters completely and 921which folds case. 922 923Perl uses the platform's C library collation functions C<strcoll()> and 924C<strxfrm()>. That means you get whatever they give. On some 925platforms, these functions work well on UTF-8 locales, giving 926a reasonable default collation for the code points that are important in 927that locale. (And if they aren't working well, the problem may only be 928that the locale definition is deficient, so can be fixed by using a 929better definition file. Unicode's definitions (see L</Freely available 930locale definitions>) provide reasonable UTF-8 locale collation 931definitions.) Starting in Perl v5.26, Perl's use of these functions has 932been made more seamless. This may be sufficient for your needs. For 933more control, and to make sure strings containing any code point (not 934just the ones important in the locale) collate properly, the 935L<Unicode::Collate> module is suggested. 936 937In non-UTF-8 locales (hence single byte), code points above 0xFF are 938technically invalid. But if present, again starting in v5.26, they will 939collate to the same position as the highest valid code point does. This 940generally gives good results, but the collation order may be skewed if 941the valid code point gets special treatment when it forms particular 942sequences with other characters as defined by the locale. 943When two strings collate identically, the code point order is used as a 944tie breaker. 945 946If Perl detects that there are problems with the locale collation order, 947it reverts to using non-locale collation rules for that locale. 948 949If you have a single string that you want to check for "equality in 950locale" against several others, you might think you could gain a little 951efficiency by using C<POSIX::strxfrm()> in conjunction with C<eq>: 952 953 use POSIX qw(strxfrm); 954 $xfrm_string = strxfrm("Mixed-case string"); 955 print "locale collation ignores spaces\n" 956 if $xfrm_string eq strxfrm("Mixed-casestring"); 957 print "locale collation ignores hyphens\n" 958 if $xfrm_string eq strxfrm("Mixedcase string"); 959 print "locale collation ignores case\n" 960 if $xfrm_string eq strxfrm("mixed-case string"); 961 962C<strxfrm()> takes a string and maps it into a transformed string for use 963in char-by-char comparisons against other transformed strings during 964collation. "Under the hood", locale-affected Perl comparison operators 965call C<strxfrm()> for both operands, then do a char-by-char 966comparison of the transformed strings. By calling C<strxfrm()> explicitly 967and using a non locale-affected comparison, the example attempts to save 968a couple of transformations. But in fact, it doesn't save anything: Perl 969magic (see L<perlguts/Magic Variables>) creates the transformed version of a 970string the first time it's needed in a comparison, then keeps this version around 971in case it's needed again. An example rewritten the easy way with 972C<cmp> runs just about as fast. It also copes with null characters 973embedded in strings; if you call C<strxfrm()> directly, it treats the first 974null it finds as a terminator. Don't expect the transformed strings 975it produces to be portable across systems--or even from one revision 976of your operating system to the next. In short, don't call C<strxfrm()> 977directly: let Perl do it for you. 978 979Note: C<use locale> isn't shown in some of these examples because it isn't 980needed: C<strcoll()> and C<strxfrm()> are POSIX:: functions 981which use the standard system-supplied C<libc> functions that 982always obey the current C<LC_COLLATE> locale. 983 984=head2 Category C<LC_CTYPE>: Character Types 985 986In the scope of a S<C<use locale>> form that includes C<LC_CTYPE>, Perl 987obeys the C<LC_CTYPE> locale 988setting. This controls the application's notion of which characters are 989alphabetic, numeric, punctuation, I<etc>. This affects Perl's C<\w> 990regular expression metanotation, 991which stands for alphanumeric characters--that is, alphabetic, 992numeric, and the platform's native underscore. 993(Consult L<perlre> for more information about 994regular expressions.) Thanks to C<LC_CTYPE>, depending on your locale 995setting, characters like "E<aelig>", "E<eth>", "E<szlig>", and 996"E<oslash>" may be understood as C<\w> characters. 997It also affects things like C<\s>, C<\D>, and the POSIX character 998classes, like C<[[:graph:]]>. (See L<perlrecharclass> for more 999information on all these.) 1000 1001The C<LC_CTYPE> locale also provides the map used in transliterating 1002characters between lower and uppercase. This affects the case-mapping 1003functions--C<fc()>, C<lc()>, C<lcfirst()>, C<uc()>, and C<ucfirst()>; 1004case-mapping 1005interpolation with C<\F>, C<\l>, C<\L>, C<\u>, or C<\U> in double-quoted 1006strings and C<s///> substitutions; and case-insensitive regular expression 1007pattern matching using the C<i> modifier. 1008 1009Starting in v5.20, Perl supports UTF-8 locales for C<LC_CTYPE>, but 1010otherwise Perl only supports single-byte locales, such as the ISO 8859 1011series. This means that wide character locales, for example for Asian 1012languages, are not well-supported. Use of these locales may cause core 1013dumps. If the platform has the capability for Perl to detect such a 1014locale, starting in Perl v5.22, L<Perl will warn, default 1015enabled|warnings/Category Hierarchy>, using the C<locale> warning 1016category, whenever such a locale is switched into. The UTF-8 locale 1017support is actually a 1018superset of POSIX locales, because it is really full Unicode behavior 1019as if no C<LC_CTYPE> locale were in effect at all (except for tainting; 1020see L</SECURITY>). POSIX locales, even UTF-8 ones, 1021are lacking certain concepts in Unicode, such as the idea that changing 1022the case of a character could expand to be more than one character. 1023Perl in a UTF-8 locale, will give you that expansion. Prior to v5.20, 1024Perl treated a UTF-8 locale on some platforms like an ISO 8859-1 one, 1025with some restrictions, and on other platforms more like the "C" locale. 1026For releases v5.16 and v5.18, C<S<use locale 'not_characters>> could be 1027used as a workaround for this (see L</Unicode and UTF-8>). 1028 1029Note that there are quite a few things that are unaffected by the 1030current locale. Any literal character is the native character for the 1031given platform. Hence 'A' means the character at code point 65 on ASCII 1032platforms, and 193 on EBCDIC. That may or may not be an 'A' in the 1033current locale, if that locale even has an 'A'. 1034Similarly, all the escape sequences for particular characters, 1035C<\n> for example, always mean the platform's native one. This means, 1036for example, that C<\N> in regular expressions (every character 1037but new-line) works on the platform character set. 1038 1039Starting in v5.22, Perl will by default warn when switching into a 1040locale that redefines any ASCII printable character (plus C<\t> and 1041C<\n>) into a different class than expected. This is likely to 1042happen on modern locales only on EBCDIC platforms, where, for example, 1043a CCSID 0037 locale on a CCSID 1047 machine moves C<"[">, but it can 1044happen on ASCII platforms with the ISO 646 and other 10457-bit locales that are essentially obsolete. Things may still work, 1046depending on what features of Perl are used by the program. For 1047example, in the example from above where C<"|"> becomes a C<\w>, and 1048there are no regular expressions where this matters, the program may 1049still work properly. The warning lists all the characters that 1050it can determine could be adversely affected. 1051 1052B<Note:> A broken or malicious C<LC_CTYPE> locale definition may result 1053in clearly ineligible characters being considered to be alphanumeric by 1054your application. For strict matching of (mundane) ASCII letters and 1055digits--for example, in command strings--locale-aware applications 1056should use C<\w> with the C</a> regular expression modifier. See L</"SECURITY">. 1057 1058=head2 Category C<LC_NUMERIC>: Numeric Formatting 1059 1060After a proper C<POSIX::setlocale()> call, and within the scope 1061of a C<use locale> form that includes numerics, Perl obeys the 1062C<LC_NUMERIC> locale information, which controls an application's idea 1063of how numbers should be formatted for human readability. 1064In most implementations the only effect is to 1065change the character used for the decimal point--perhaps from "." to ",". 1066The functions aren't aware of such niceties as thousands separation and 1067so on. (See L</The localeconv function> if you care about these things.) 1068 1069 use POSIX qw(strtod setlocale LC_NUMERIC); 1070 use locale; 1071 1072 setlocale LC_NUMERIC, ""; 1073 1074 $n = 5/2; # Assign numeric 2.5 to $n 1075 1076 $x = " $n"; # Locale-dependent conversion to string 1077 1078 print "half five is $n\n"; # Locale-dependent output 1079 1080 printf "half five is %g\n", $n; # Locale-dependent output 1081 1082 print "DECIMAL POINT IS COMMA\n" 1083 if $n == (strtod("2,5"))[0]; # Locale-dependent conversion 1084 1085See also L<I18N::Langinfo> and C<RADIXCHAR>. 1086 1087=head2 Category C<LC_MONETARY>: Formatting of monetary amounts 1088 1089The C standard defines the C<LC_MONETARY> category, but not a function 1090that is affected by its contents. (Those with experience of standards 1091committees will recognize that the working group decided to punt on the 1092issue. POSIX 2001 added the C<strfmon()> function to format currency 1093amounts, but there is no official function to parse strings representing 1094currency values.) 1095 1096Perl essentially takes no notice of this category. On POSIX systems, you 1097can call C<strfmon()> from XS code to create formatted strings, and/or you 1098you can query the C<LC_MONETARY> locale-specific values with 1099L</The localeconv function> and use the information that it returns in your 1100application's own formatting of currency amounts. However, you may well 1101find that the information, voluminous and complex though it may be, still 1102does not quite meet your requirements: currency formatting is a hard nut 1103to crack. 1104 1105See also C<CRNCYSTR> in L<I18N::Langinfo>. 1106 1107=head2 Category C<LC_TIME>: Respresentation of time 1108 1109Output produced by C<POSIX::strftime()>, which builds a formatted 1110human-readable date/time string, is affected by the current C<LC_TIME> 1111locale. Thus, in a French locale, the output produced by the C<%B> 1112format element (full month name) for the first month of the year would 1113be "janvier". Here's how to get a list of long month names in the 1114current locale: 1115 1116 use POSIX qw(strftime); 1117 for (0..11) { 1118 $long_month_name[$_] = 1119 strftime("%B", 0, 0, 0, 1, $_, 96); 1120 } 1121 1122Note: C<use locale> isn't needed in this example: C<strftime()> is a POSIX:: 1123function which uses the standard system-supplied C<libc> function that 1124always obeys the current C<LC_TIME> locale. 1125 1126See also L<I18N::Langinfo> and C<ABDAY_1>..C<ABDAY_7>, C<DAY_1>..C<DAY_7>, 1127C<ABMON_1>..C<ABMON_12>, and C<ABMON_1>..C<ABMON_12>. 1128 1129There is also the libc C<strptime()> function defined starting in POSIX 11302001 (it's not in Windows) that parses formatted time strings. There is 1131currently no pure perl access to this function, so you need to write XS 1132code to use it. 1133 1134=head2 Category C<LC_MESSAGES>: System messages 1135 1136This category is used by perl to create a string describing a system 1137error number, such as what you would get by saying 1138L<C<"$!">|perlvar/$ERRNO> or L<C<"$^E">|perlvar/$EXTENDED_OS_ERROR>. 1139On some systems and locales, the string will be in the language of the 1140locale given by C<LC_MESSAGES>. But not many systems have bothered to 1141install such translations for all locales available on the system. If 1142no translation is available for a given locale, the string will be in 1143English. See L<Errno> for information about portably using error codes. 1144 1145The other categories mentioned so far are required to exist in any 1146platform on which Perl can run. But this category is a POSIX extension, 1147and Perl runs on platforms, Windows, for example, that don't have it. On 1148such platforms the underlying language for the system errors will be 1149whatever C<LC_CTYPE> gives, or English. 1150 1151This category in conjunction with L<I18N::Langinfo> can be used to 1152output yes/no in its locale's language, and to parse strings that 1153contain "yes" or "no" in that language. 1154 1155=head2 Other categories 1156 1157Some platforms have additional categories. These are not used by Perl 1158itself. L<I18N::Langinfo> may be used to query them, yielding stub 1159values on platforms where they don't exist. But again note that things 1160Perl interacts with may use these, including extensions outside the 1161standard Perl distribution, and by the operating system and its 1162utilities. 1163 1164=head1 SECURITY 1165 1166Although the main discussion of Perl security issues can be found in 1167L<perlsec>, a discussion of Perl's locale handling would be incomplete 1168if it did not draw your attention to locale-dependent security issues. 1169Locales--particularly on systems that allow unprivileged users to 1170build their own locales--are untrustworthy. A malicious (or just plain 1171broken) locale can make a locale-aware application give unexpected 1172results. Here are a few possibilities: 1173 1174=over 4 1175 1176=item * 1177 1178Regular expression checks for safe file names or mail addresses using 1179C<\w> may be spoofed by an C<LC_CTYPE> locale that claims that 1180characters such as C<"E<gt>"> and C<"|"> are alphanumeric. 1181 1182=item * 1183 1184String interpolation with case-mapping, as in, say, C<$dest = 1185"C:\U$name.$ext">, may produce dangerous results if a bogus C<LC_CTYPE> 1186case-mapping table is in effect. 1187 1188=item * 1189 1190A sneaky C<LC_COLLATE> locale could result in the names of students with 1191"D" grades appearing ahead of those with "A"s. 1192 1193=item * 1194 1195An application that takes the trouble to use information in 1196C<LC_MONETARY> may format debits as if they were credits and vice versa 1197if that locale has been subverted. Or it might make payments in US 1198dollars instead of Hong Kong dollars. 1199 1200=item * 1201 1202The date and day names in dates formatted by C<strftime()> could be 1203manipulated to advantage by a malicious user able to subvert the 1204C<LC_TIME> locale. ("Look--it says I wasn't in the building on 1205Sunday.") 1206 1207=back 1208 1209Such dangers are not peculiar to the locale system: any aspect of an 1210application's environment which may be modified maliciously presents 1211similar challenges. Similarly, they are not specific to Perl: any 1212programming language that allows you to write programs that take 1213account of their environment exposes you to these issues. 1214 1215Perl cannot protect you from all possibilities shown in the 1216examples--there is no substitute for your own vigilance--but, when 1217C<use locale> is in effect, Perl uses the tainting mechanism (see 1218L<perlsec>) to mark string results that become locale-dependent, and 1219which may be untrustworthy in consequence. 1220 1221Note that it is possible to compile Perl without taint support, 1222in which case all taint features silently do nothing. 1223 1224Here is a summary of the tainting behavior of operators and functions 1225that may be affected by the locale: 1226 1227=over 4 1228 1229=item * 1230 1231B<Comparison operators> (C<lt>, C<le>, C<ge>, C<gt> and C<cmp>): 1232 1233Scalar true/false (or less/equal/greater) result is never tainted. 1234 1235=item * 1236 1237B<Case-mapping interpolation> (with C<\l>, C<\L>, C<\u>, C<\U>, or C<\F>) 1238 1239The result string containing interpolated material is tainted if 1240a C<use locale> form that includes C<LC_CTYPE> is in effect. 1241 1242=item * 1243 1244B<Matching operator> (C<m//>): 1245 1246Scalar true/false result never tainted. 1247 1248All subpatterns, either delivered as a list-context result or as C<$1> 1249I<etc>., are tainted if a C<use locale> form that includes 1250C<LC_CTYPE> is in effect, and the subpattern 1251regular expression contains a locale-dependent construct. These 1252constructs include C<\w> (to match an alphanumeric character), C<\W> 1253(non-alphanumeric character), C<\b> and C<\B> (word-boundary and 1254non-boundardy, which depend on what C<\w> and C<\W> match), C<\s> 1255(whitespace character), C<\S> (non whitespace character), C<\d> and 1256C<\D> (digits and non-digits), and the POSIX character classes, such as 1257C<[:alpha:]> (see L<perlrecharclass/POSIX Character Classes>). 1258 1259Tainting is also likely if the pattern is to be matched 1260case-insensitively (via C</i>). The exception is if all the code points 1261to be matched this way are above 255 and do not have folds under Unicode 1262rules to below 256. Tainting is not done for these because Perl 1263only uses Unicode rules for such code points, and those rules are the 1264same no matter what the current locale. 1265 1266The matched-pattern variables, C<$&>, C<$`> (pre-match), C<$'> 1267(post-match), and C<$+> (last match) also are tainted. 1268 1269=item * 1270 1271B<Substitution operator> (C<s///>): 1272 1273Has the same behavior as the match operator. Also, the left 1274operand of C<=~> becomes tainted when a C<use locale> 1275form that includes C<LC_CTYPE> is in effect, if modified as 1276a result of a substitution based on a regular 1277expression match involving any of the things mentioned in the previous 1278item, or of case-mapping, such as C<\l>, C<\L>,C<\u>, C<\U>, or C<\F>. 1279 1280=item * 1281 1282B<Output formatting functions> (C<printf()> and C<write()>): 1283 1284Results are never tainted because otherwise even output from print, 1285for example C<print(1/7)>, should be tainted if C<use locale> is in 1286effect. 1287 1288=item * 1289 1290B<Case-mapping functions> (C<lc()>, C<lcfirst()>, C<uc()>, C<ucfirst()>): 1291 1292Results are tainted if a C<use locale> form that includes C<LC_CTYPE> is 1293in effect. 1294 1295=item * 1296 1297B<POSIX locale-dependent functions> (C<localeconv()>, C<strcoll()>, 1298C<strftime()>, C<strxfrm()>): 1299 1300Results are never tainted. 1301 1302=back 1303 1304Three examples illustrate locale-dependent tainting. 1305The first program, which ignores its locale, won't run: a value taken 1306directly from the command line may not be used to name an output file 1307when taint checks are enabled. 1308 1309 #/usr/local/bin/perl -T 1310 # Run with taint checking 1311 1312 # Command line sanity check omitted... 1313 $tainted_output_file = shift; 1314 1315 open(F, ">$tainted_output_file") 1316 or warn "Open of $tainted_output_file failed: $!\n"; 1317 1318The program can be made to run by "laundering" the tainted value through 1319a regular expression: the second example--which still ignores locale 1320information--runs, creating the file named on its command line 1321if it can. 1322 1323 #/usr/local/bin/perl -T 1324 1325 $tainted_output_file = shift; 1326 $tainted_output_file =~ m%[\w/]+%; 1327 $untainted_output_file = $&; 1328 1329 open(F, ">$untainted_output_file") 1330 or warn "Open of $untainted_output_file failed: $!\n"; 1331 1332Compare this with a similar but locale-aware program: 1333 1334 #/usr/local/bin/perl -T 1335 1336 $tainted_output_file = shift; 1337 use locale; 1338 $tainted_output_file =~ m%[\w/]+%; 1339 $localized_output_file = $&; 1340 1341 open(F, ">$localized_output_file") 1342 or warn "Open of $localized_output_file failed: $!\n"; 1343 1344This third program fails to run because C<$&> is tainted: it is the result 1345of a match involving C<\w> while C<use locale> is in effect. 1346 1347=head1 ENVIRONMENT 1348 1349=over 12 1350 1351=item PERL_SKIP_LOCALE_INIT 1352 1353This environment variable, available starting in Perl v5.20, if set 1354(to any value), tells Perl to not use the rest of the 1355environment variables to initialize with. Instead, Perl uses whatever 1356the current locale settings are. This is particularly useful in 1357embedded environments, see 1358L<perlembed/Using embedded Perl with POSIX locales>. 1359 1360=item PERL_BADLANG 1361 1362A string that can suppress Perl's warning about failed locale settings 1363at startup. Failure can occur if the locale support in the operating 1364system is lacking (broken) in some way--or if you mistyped the name of 1365a locale when you set up your environment. If this environment 1366variable is absent, or has a value other than "0" or "", Perl will 1367complain about locale setting failures. 1368 1369B<NOTE>: C<PERL_BADLANG> only gives you a way to hide the warning message. 1370The message tells about some problem in your system's locale support, 1371and you should investigate what the problem is. 1372 1373=back 1374 1375The following environment variables are not specific to Perl: They are 1376part of the standardized (ISO C, XPG4, POSIX 1.c) C<setlocale()> method 1377for controlling an application's opinion on data. Windows is non-POSIX, 1378but Perl arranges for the following to work as described anyway. 1379If the locale given by an environment variable is not valid, Perl tries 1380the next lower one in priority. If none are valid, on Windows, the 1381system default locale is then tried. If all else fails, the C<"C"> 1382locale is used. If even that doesn't work, something is badly broken, 1383but Perl tries to forge ahead with whatever the locale settings might 1384be. 1385 1386=over 12 1387 1388=item C<LC_ALL> 1389 1390C<LC_ALL> is the "override-all" locale environment variable. If 1391set, it overrides all the rest of the locale environment variables. 1392 1393=item C<LANGUAGE> 1394 1395B<NOTE>: C<LANGUAGE> is a GNU extension, it affects you only if you 1396are using the GNU libc. This is the case if you are using e.g. Linux. 1397If you are using "commercial" Unixes you are most probably I<not> 1398using GNU libc and you can ignore C<LANGUAGE>. 1399 1400However, in the case you are using C<LANGUAGE>: it affects the 1401language of informational, warning, and error messages output by 1402commands (in other words, it's like C<LC_MESSAGES>) but it has higher 1403priority than C<LC_ALL>. Moreover, it's not a single value but 1404instead a "path" (":"-separated list) of I<languages> (not locales). 1405See the GNU C<gettext> library documentation for more information. 1406 1407=item C<LC_CTYPE> 1408 1409In the absence of C<LC_ALL>, C<LC_CTYPE> chooses the character type 1410locale. In the absence of both C<LC_ALL> and C<LC_CTYPE>, C<LANG> 1411chooses the character type locale. 1412 1413=item C<LC_COLLATE> 1414 1415In the absence of C<LC_ALL>, C<LC_COLLATE> chooses the collation 1416(sorting) locale. In the absence of both C<LC_ALL> and C<LC_COLLATE>, 1417C<LANG> chooses the collation locale. 1418 1419=item C<LC_MONETARY> 1420 1421In the absence of C<LC_ALL>, C<LC_MONETARY> chooses the monetary 1422formatting locale. In the absence of both C<LC_ALL> and C<LC_MONETARY>, 1423C<LANG> chooses the monetary formatting locale. 1424 1425=item C<LC_NUMERIC> 1426 1427In the absence of C<LC_ALL>, C<LC_NUMERIC> chooses the numeric format 1428locale. In the absence of both C<LC_ALL> and C<LC_NUMERIC>, C<LANG> 1429chooses the numeric format. 1430 1431=item C<LC_TIME> 1432 1433In the absence of C<LC_ALL>, C<LC_TIME> chooses the date and time 1434formatting locale. In the absence of both C<LC_ALL> and C<LC_TIME>, 1435C<LANG> chooses the date and time formatting locale. 1436 1437=item C<LANG> 1438 1439C<LANG> is the "catch-all" locale environment variable. If it is set, it 1440is used as the last resort after the overall C<LC_ALL> and the 1441category-specific C<LC_I<foo>>. 1442 1443=back 1444 1445=head2 Examples 1446 1447The C<LC_NUMERIC> controls the numeric output: 1448 1449 use locale; 1450 use POSIX qw(locale_h); # Imports setlocale() and the LC_ constants. 1451 setlocale(LC_NUMERIC, "fr_FR") or die "Pardon"; 1452 printf "%g\n", 1.23; # If the "fr_FR" succeeded, probably shows 1,23. 1453 1454and also how strings are parsed by C<POSIX::strtod()> as numbers: 1455 1456 use locale; 1457 use POSIX qw(locale_h strtod); 1458 setlocale(LC_NUMERIC, "de_DE") or die "Entschuldigung"; 1459 my $x = strtod("2,34") + 5; 1460 print $x, "\n"; # Probably shows 7,34. 1461 1462=head1 NOTES 1463 1464=head2 String C<eval> and C<LC_NUMERIC> 1465 1466A string L<eval|perlfunc/eval EXPR> parses its expression as standard 1467Perl. It is therefore expecting the decimal point to be a dot. If 1468C<LC_NUMERIC> is set to have this be a comma instead, the parsing will 1469be confused, perhaps silently. 1470 1471 use locale; 1472 use POSIX qw(locale_h); 1473 setlocale(LC_NUMERIC, "fr_FR") or die "Pardon"; 1474 my $x = 1.2; 1475 print eval "$x + 1.5"; 1476 print "\n"; 1477 1478prints C<13,5>. This is because in that locale, the comma is the 1479decimal point character. The C<eval> thus expands to: 1480 1481 eval "1,2 + 1.5" 1482 1483and the result is not what you likely expected. No warnings are 1484generated. If you do string C<eval>'s within the scope of 1485S<C<use locale>>, you should instead change the C<eval> line to do 1486something like: 1487 1488 print eval "no locale; $x + 1.5"; 1489 1490This prints C<2.7>. 1491 1492You could also exclude C<LC_NUMERIC>, if you don't need it, by 1493 1494 use locale ':!numeric'; 1495 1496=head2 Backward compatibility 1497 1498Versions of Perl prior to 5.004 B<mostly> ignored locale information, 1499generally behaving as if something similar to the C<"C"> locale were 1500always in force, even if the program environment suggested otherwise 1501(see L</The setlocale function>). By default, Perl still behaves this 1502way for backward compatibility. If you want a Perl application to pay 1503attention to locale information, you B<must> use the S<C<use locale>> 1504pragma (see L</The "use locale" pragma>) or, in the unlikely event 1505that you want to do so for just pattern matching, the 1506C</l> regular expression modifier (see L<perlre/Character set 1507modifiers>) to instruct it to do so. 1508 1509Versions of Perl from 5.002 to 5.003 did use the C<LC_CTYPE> 1510information if available; that is, C<\w> did understand what 1511were the letters according to the locale environment variables. 1512The problem was that the user had no control over the feature: 1513if the C library supported locales, Perl used them. 1514 1515=head2 I18N:Collate obsolete 1516 1517In versions of Perl prior to 5.004, per-locale collation was possible 1518using the C<I18N::Collate> library module. This module is now mildly 1519obsolete and should be avoided in new applications. The C<LC_COLLATE> 1520functionality is now integrated into the Perl core language: One can 1521use locale-specific scalar data completely normally with C<use locale>, 1522so there is no longer any need to juggle with the scalar references of 1523C<I18N::Collate>. 1524 1525=head2 Sort speed and memory use impacts 1526 1527Comparing and sorting by locale is usually slower than the default 1528sorting; slow-downs of two to four times have been observed. It will 1529also consume more memory: once a Perl scalar variable has participated 1530in any string comparison or sorting operation obeying the locale 1531collation rules, it will take 3-15 times more memory than before. (The 1532exact multiplier depends on the string's contents, the operating system 1533and the locale.) These downsides are dictated more by the operating 1534system's implementation of the locale system than by Perl. 1535 1536=head2 Freely available locale definitions 1537 1538The Unicode CLDR project extracts the POSIX portion of many of its 1539locales, available at 1540 1541 https://unicode.org/Public/cldr/2.0.1/ 1542 1543(Newer versions of CLDR require you to compute the POSIX data yourself. 1544See L<https://unicode.org/Public/cldr/latest/>.) 1545 1546There is a large collection of locale definitions at: 1547 1548 http://std.dkuug.dk/i18n/WG15-collection/locales/ 1549 1550You should be aware that it is 1551unsupported, and is not claimed to be fit for any purpose. If your 1552system allows installation of arbitrary locales, you may find the 1553definitions useful as they are, or as a basis for the development of 1554your own locales. 1555 1556=head2 I18n and l10n 1557 1558"Internationalization" is often abbreviated as B<i18n> because its first 1559and last letters are separated by eighteen others. (You may guess why 1560the internalin ... internaliti ... i18n tends to get abbreviated.) In 1561the same way, "localization" is often abbreviated to B<l10n>. 1562 1563=head2 An imperfect standard 1564 1565Internationalization, as defined in the C and POSIX standards, can be 1566criticized as incomplete and ungainly. They also have a tendency, like 1567standards groups, to divide the world into nations, when we all know 1568that the world can equally well be divided into bankers, bikers, gamers, 1569and so on. 1570 1571=head1 Unicode and UTF-8 1572 1573The support of Unicode is new starting from Perl version v5.6, and more fully 1574implemented in versions v5.8 and later. See L<perluniintro>. 1575 1576Starting in Perl v5.20, UTF-8 locales are supported in Perl, except 1577C<LC_COLLATE> is only partially supported; collation support is improved 1578in Perl v5.26 to a level that may be sufficient for your needs 1579(see L</Category C<LC_COLLATE>: Collation: Text Comparisons and Sorting>). 1580 1581If you have Perl v5.16 or v5.18 and can't upgrade, you can use 1582 1583 use locale ':not_characters'; 1584 1585When this form of the pragma is used, only the non-character portions of 1586locales are used by Perl, for example C<LC_NUMERIC>. Perl assumes that 1587you have translated all the characters it is to operate on into Unicode 1588(actually the platform's native character set (ASCII or EBCDIC) plus 1589Unicode). For data in files, this can conveniently be done by also 1590specifying 1591 1592 use open ':locale'; 1593 1594This pragma arranges for all inputs from files to be translated into 1595Unicode from the current locale as specified in the environment (see 1596L</ENVIRONMENT>), and all outputs to files to be translated back 1597into the locale. (See L<open>). On a per-filehandle basis, you can 1598instead use the L<PerlIO::locale> module, or the L<Encode::Locale> 1599module, both available from CPAN. The latter module also has methods to 1600ease the handling of C<ARGV> and environment variables, and can be used 1601on individual strings. If you know that all your locales will be 1602UTF-8, as many are these days, you can use the 1603L<B<-C>|perlrun/-C [numberE<sol>list]> command line switch. 1604 1605This form of the pragma allows essentially seamless handling of locales 1606with Unicode. The collation order will be by Unicode code point order. 1607L<Unicode::Collate> can be used to get Unicode rules collation. 1608 1609All the modules and switches just described can be used in v5.20 with 1610just plain C<use locale>, and, should the input locales not be UTF-8, 1611you'll get the less than ideal behavior, described below, that you get 1612with pre-v5.16 Perls, or when you use the locale pragma without the 1613C<:not_characters> parameter in v5.16 and v5.18. If you are using 1614exclusively UTF-8 locales in v5.20 and higher, the rest of this section 1615does not apply to you. 1616 1617There are two cases, multi-byte and single-byte locales. First 1618multi-byte: 1619 1620The only multi-byte (or wide character) locale that Perl is ever likely 1621to support is UTF-8. This is due to the difficulty of implementation, 1622the fact that high quality UTF-8 locales are now published for every 1623area of the world (L<https://unicode.org/Public/cldr/2.0.1/> for 1624ones that are already set-up, but from an earlier version; 1625L<https://unicode.org/Public/cldr/latest/> for the most up-to-date, but 1626you have to extract the POSIX information yourself), and 1627failing all that, you can use the L<Encode> module to translate to/from 1628your locale. So, you'll have to do one of those things if you're using 1629one of these locales, such as Big5 or Shift JIS. For UTF-8 locales, in 1630Perls (pre v5.20) that don't have full UTF-8 locale support, they may 1631work reasonably well (depending on your C library implementation) 1632simply because both 1633they and Perl store characters that take up multiple bytes the same way. 1634However, some, if not most, C library implementations may not process 1635the characters in the upper half of the Latin-1 range (128 - 255) 1636properly under C<LC_CTYPE>. To see if a character is a particular type 1637under a locale, Perl uses the functions like C<isalnum()>. Your C 1638library may not work for UTF-8 locales with those functions, instead 1639only working under the newer wide library functions like C<iswalnum()>, 1640which Perl does not use. 1641These multi-byte locales are treated like single-byte locales, and will 1642have the restrictions described below. Starting in Perl v5.22 a warning 1643message is raised when Perl detects a multi-byte locale that it doesn't 1644fully support. 1645 1646For single-byte locales, 1647Perl generally takes the tack to use locale rules on code points that can fit 1648in a single byte, and Unicode rules for those that can't (though this 1649isn't uniformly applied, see the note at the end of this section). This 1650prevents many problems in locales that aren't UTF-8. Suppose the locale 1651is ISO8859-7, Greek. The character at 0xD7 there is a capital Chi. But 1652in the ISO8859-1 locale, Latin1, it is a multiplication sign. The POSIX 1653regular expression character class C<[[:alpha:]]> will magically match 16540xD7 in the Greek locale but not in the Latin one. 1655 1656However, there are places where this breaks down. Certain Perl constructs are 1657for Unicode only, such as C<\p{Alpha}>. They assume that 0xD7 always has its 1658Unicode meaning (or the equivalent on EBCDIC platforms). Since Latin1 is a 1659subset of Unicode and 0xD7 is the multiplication sign in both Latin1 and 1660Unicode, C<\p{Alpha}> will never match it, regardless of locale. A similar 1661issue occurs with C<\N{...}>. Prior to v5.20, it is therefore a bad 1662idea to use C<\p{}> or 1663C<\N{}> under plain C<use locale>--I<unless> you can guarantee that the 1664locale will be ISO8859-1. Use POSIX character classes instead. 1665 1666Another problem with this approach is that operations that cross the 1667single byte/multiple byte boundary are not well-defined, and so are 1668disallowed. (This boundary is between the codepoints at 255/256.) 1669For example, lower casing LATIN CAPITAL LETTER Y WITH DIAERESIS (U+0178) 1670should return LATIN SMALL LETTER Y WITH DIAERESIS (U+00FF). But in the 1671Greek locale, for example, there is no character at 0xFF, and Perl 1672has no way of knowing what the character at 0xFF is really supposed to 1673represent. Thus it disallows the operation. In this mode, the 1674lowercase of U+0178 is itself. 1675 1676The same problems ensue if you enable automatic UTF-8-ification of your 1677standard file handles, default C<open()> layer, and C<@ARGV> on non-ISO8859-1, 1678non-UTF-8 locales (by using either the B<-C> command line switch or the 1679C<PERL_UNICODE> environment variable; see 1680L<perlrun|perlrun/-C [numberE<sol>list]>). 1681Things are read in as UTF-8, which would normally imply a Unicode 1682interpretation, but the presence of a locale causes them to be interpreted 1683in that locale instead. For example, a 0xD7 code point in the Unicode 1684input, which should mean the multiplication sign, won't be interpreted by 1685Perl that way under the Greek locale. This is not a problem 1686I<provided> you make certain that all locales will always and only be either 1687an ISO8859-1, or, if you don't have a deficient C library, a UTF-8 locale. 1688 1689Still another problem is that this approach can lead to two code 1690points meaning the same character. Thus in a Greek locale, both U+03A7 1691and U+00D7 are GREEK CAPITAL LETTER CHI. 1692 1693Because of all these problems, starting in v5.22, Perl will raise a 1694warning if a multi-byte (hence Unicode) code point is used when a 1695single-byte locale is in effect. (Although it doesn't check for this if 1696doing so would unreasonably slow execution down.) 1697 1698Vendor locales are notoriously buggy, and it is difficult for Perl to test 1699its locale-handling code because this interacts with code that Perl has no 1700control over; therefore the locale-handling code in Perl may be buggy as 1701well. (However, the Unicode-supplied locales should be better, and 1702there is a feed back mechanism to correct any problems. See 1703L</Freely available locale definitions>.) 1704 1705If you have Perl v5.16, the problems mentioned above go away if you use 1706the C<:not_characters> parameter to the locale pragma (except for vendor 1707bugs in the non-character portions). If you don't have v5.16, and you 1708I<do> have locales that work, using them may be worthwhile for certain 1709specific purposes, as long as you keep in mind the gotchas already 1710mentioned. For example, if the collation for your locales works, it 1711runs faster under locales than under L<Unicode::Collate>; and you gain 1712access to such things as the local currency symbol and the names of the 1713months and days of the week. (But to hammer home the point, in v5.16, 1714you get this access without the downsides of locales by using the 1715C<:not_characters> form of the pragma.) 1716 1717Note: The policy of using locale rules for code points that can fit in a 1718byte, and Unicode rules for those that can't is not uniformly applied. 1719Pre-v5.12, it was somewhat haphazard; in v5.12 it was applied fairly 1720consistently to regular expression matching except for bracketed 1721character classes; in v5.14 it was extended to all regex matches; and in 1722v5.16 to the casing operations such as C<\L> and C<uc()>. For 1723collation, in all releases so far, the system's C<strxfrm()> function is 1724called, and whatever it does is what you get. Starting in v5.26, various 1725bugs are fixed with the way perl uses this function. 1726 1727=head1 BUGS 1728 1729=head2 Collation of strings containing embedded C<NUL> characters 1730 1731C<NUL> characters will sort the same as the lowest collating control 1732character does, or to C<"\001"> in the unlikely event that there are no 1733control characters at all in the locale. In cases where the strings 1734don't contain this non-C<NUL> control, the results will be correct, and 1735in many locales, this control, whatever it might be, will rarely be 1736encountered. But there are cases where a C<NUL> should sort before this 1737control, but doesn't. If two strings do collate identically, the one 1738containing the C<NUL> will sort to earlier. Prior to 5.26, there were 1739more bugs. 1740 1741=head2 C<LANGUAGE> 1742 1743As stated above, Perl ignores this environment variable. 1744 1745=head2 Embedded perls and multi-threaded 1746 1747You should not change the locale after startup on a platform where 1748C<${^SAFE_LOCALES}> is 0. It will always be 1 on an unthreaded 1749platform. 1750 1751XS writers should refer to L<perlclib/Dealing with embedded perls and threads>. 1752 1753=head2 Broken systems 1754 1755On a few remaining systems, the operating system's locale support 1756is broken and cannot be fixed or used by Perl. Such deficiencies can 1757and will result in mysterious hangs and/or Perl core dumps when 1758C<use locale> is in effect. When confronted with such a system, 1759please report in excruciating detail to 1760<L<https://github.com/Perl/perl5/issues>>, and 1761also contact your vendor: bug fixes may exist for these problems 1762in your operating system. Sometimes such bug fixes are called an 1763operating system upgrade. If you have the source for Perl, include in 1764the bug report the output of the test described above in L</Testing 1765for broken locales>. 1766 1767=head1 SEE ALSO 1768 1769L<I18N::Langinfo>, L<perluniintro>, L<perlunicode>, L<open>, 1770L<POSIX/localeconv>, 1771L<POSIX/setlocale>, L<POSIX/strcoll>, L<POSIX/strftime>, 1772L<POSIX/strtod>, L<POSIX/strxfrm>. 1773 1774For special considerations when Perl is embedded in a C program, 1775see L<perlembed/Using embedded Perl with POSIX locales>. 1776 1777=head1 HISTORY 1778 1779Jarkko Hietaniemi's original F<perli18n.pod> heavily hacked by Dominic 1780Dunlop, assisted by the perl5-porters. Prose worked over a bit by 1781Tom Christiansen, and now maintained by Perl 5 porters. 1782