Cari di Perl 
    Perl Tutorial
Daftar Isi
(Sebelumnya) Writing portable PerlPerl Unicode introduction (Berikutnya)
Language Reference

Perl locale handling (internationalization and localization)

Daftar Isi

NAME

perllocale - Perl locale handling (internationalization and localization)

DESCRIPTION

In the beginning there was ASCII, the "American Standard Code forInformation Interchange", which works quite well for Americans withtheir English alphabet and dollar-denominated currency. But it doesn'twork so well even for other English speakers, who may use differentcurrencies, such as the pound sterling (as the symbol for that currencyis not in ASCII); and it's hopelessly inadequate for many of thethousands of the world's other languages.

To address these deficiencies, the concept of locales was invented(formally the ISO C, XPG4, POSIX 1.c "locale system"). And applicationswere and are being written that use the locale mechanism. The process ofmaking such an application take account of its users' preferences inthese kinds of matters is called internationalization (oftenabbreviated as i18n); telling such an application about a particularset of preferences is known as localization (l10n).

Perl was extended, starting in 5.004, to support the locale system. Thisis controlled per application by using one pragma, one function call,and several environment variables.

Unfortunately, there are quite a few deficiencies with the design (andoften, the implementations) of locales, and their use for character setshas mostly been supplanted by Unicode (see perlunitut for anintroduction to that, and keep on reading here for how Unicode interactswith locales in Perl).

Perl continues to support the old locale system, and starting in v5.16,provides a hybrid way to use the Unicode character set, along with theother portions of locales that may not be so problematic.(Unicode is also creating CLDR, the "Common Locale Data Repository",http://cldr.unicode.org/ which includes more types of information thanare available in the POSIX locale system. At the time of this writing,there was no CPAN module that provides access to this XML-encoded data.However, many of its locales have the POSIX-only data extracted, and areavailable at http://unicode.org/Public/cldr/latest/.)

WHAT IS A LOCALE

A locale is a set of data that describes various aspects of how variouscommunities in the world categorize their world. These categories arebroken down into the following types (some of which include a briefnote here):

  • Category LC_NUMERIC: Numeric formatting

    This indicates how numbers should be formatted for human readability,for example the character used as the decimal point.

  • Category LC_MONETARY: Formatting of monetary amounts

     

  • Category LC_TIME: Date/Time formatting

     

  • Category LC_MESSAGES: Error and other messages

    This for the most part is beyond the scope of Perl

  • Category LC_COLLATE: Collation

    This indicates the ordering of letters for comparision and sorting.In Latin alphabets, for example, "b", generally follows "a".

  • Category LC_CTYPE: Character Types

    This indicates, for example if a character is an uppercase letter.

More details on the categories are given below in LOCALE CATEGORIES.

Together, these categories go a long way towards being able to customizea single program to run in many different locations. But there aredeficiencies, so keep reading.

PREPARING TO USE LOCALES

Perl will not use locales unless specifically requested to (see NOTES belowfor the partial exception of write()). But even if there is such arequest, all of the following must be true for it to work properly:

  • Your operating system must support the locale system. If it does,you should find that the setlocale() function is a documented part ofits C library.

  • Definitions for locales that you use must be installed. You, oryour system administrator, must make sure that this is the case. Theavailable locales, the location in which they are kept, and the mannerin which they are installed all vary from system to system. Some systemsprovide only a few, hard-wired locales and do not allow more to beadded. Others allow you to add "canned" locales provided by the systemsupplier. Still others allow you or the system administrator to defineand add arbitrary locales. (You may have to ask your supplier toprovide canned locales that are not delivered with your operatingsystem.) Read your system documentation for further illumination.

  • Perl must believe that the locale system is supported. If it does,perl -V:d_setlocale will say that the value for d_setlocale isdefine.

If you want a Perl application to process and present your dataaccording to a particular locale, the application code should includethe use locale pragma (see The use locale pragma) whereappropriate, and at least one of the following must be true:

1

The locale-determining environment variables (see ENVIRONMENT)must be correctly set up at the time the application is started, eitherby yourself or by whomever set up your system account; or

2

The application must set its own locale using the method described inThe setlocale function.

USING LOCALES

The use locale pragma

By default, Perl ignores the current locale. The use localepragma tells Perl to use the current locale for some operations.Starting in v5.16, there is an optional parameter to this pragma:

  1. use locale ':not_characters';

This parameter allows better mixing of locales and Unicode, and isdescribed fully in Unicode and UTF-8, but briefly, it tells Perl tonot use the character portions of the locale definition, that isthe LC_CTYPE and LC_COLLATE categories. Instead it will use thenative (extended by Unicode) character set. When using this parameter,you are responsible for getting the external character set translatedinto the native/Unicode one (which it already will be if it is one ofthe increasingly popular UTF-8 locales). There are convenient ways ofdoing this, as described in Unicode and UTF-8.

The current locale is set at execution time bysetlocale() described below. If that functionhasn't yet been called in the course of the program's execution, thecurrent locale is that which was determined by the ENVIRONMENT ineffect at the start of the program, except thatLC_NUMERIC is alwaysinitialized to the C locale (mentioned under Finding locales).If there is no valid environment, the current locale is undefined. Itis likely, but not necessarily, the "C" locale.

The operations that are affected by locale are:

  • Under use locale ':not_characters';
    • Format declarations (format()) use LC_NUMERIC

    • The POSIX date formatting function (strftime()) uses LC_TIME.

     

  • Under just plain use locale;

    The above operations are affected, as well as the following:

    • The comparison operators (lt, le, cmp, ge, and gt) andthe POSIX string collation functions strcoll() and strxfrm() useLC_COLLATE. sort() is also affected if used without anexplicit comparison function, because it uses cmp by default.

      Note: eq and ne are unaffected by locale: they alwaysperform a char-by-char comparison of their scalar operands. What'smore, if cmp finds that its operands are equal according to thecollation sequence specified by the current locale, it goes on toperform a char-by-char comparison, and only returns 0 (equal) if theoperands are char-for-char identical. If you really want to know whethertwo strings--which eq and cmp may consider different--are equalas far as collation in the locale is concerned, see the discussion inCategory LC_COLLATE: Collation.

    • Regular expressions and case-modification functions (uc(), lc(),ucfirst(), and lcfirst()) use LC_CTYPE

The default behavior is restored with the no locale pragma, orupon reaching the end of the block enclosing use locale.Note that use locale and use locale ':not_characters' may benested, and that what is in effect within an inner scope will revert tothe outer scope's rules at the end of the inner scope.

The string result of any operation that uses localeinformation is tainted, as it is possible for a locale to beuntrustworthy. See SECURITY.

The setlocale function

You can switch locales as often as you wish at run time with thePOSIX::setlocale() function:

  1. # This functionality not usable prior to Perl 5.004
  2. require 5.004;
  3. # Import locale-handling tool set from POSIX module.
  4. # This example uses: setlocale -- the function call
  5. # LC_CTYPE -- explained below
  6. use POSIX qw(locale_h);
  7. # query and save the old locale
  8. $old_locale = setlocale(LC_CTYPE);
  9. setlocale(LC_CTYPE, "fr_CA.ISO8859-1");
  10. # LC_CTYPE now in locale "French, Canada, codeset ISO 8859-1"
  11. setlocale(LC_CTYPE, "");
  12. # LC_CTYPE now reset to default defined by LC_ALL/LC_CTYPE/LANG
  13. # environment variables. See below for documentation.
  14. # restore the old locale
  15. setlocale(LC_CTYPE, $old_locale);

The first argument of setlocale() gives the category, the second thelocale. The category tells in what aspect of data processing youwant to apply locale-specific rules. Category names are discussed inLOCALE CATEGORIES and ENVIRONMENT. The locale is the name of acollection of customization information corresponding to a particularcombination of language, country or territory, and codeset. Read on forhints on the naming of locales: not all systems name locales as in theexample.

If no second argument is provided and the category is something elsethan LC_ALL, the function returns a string naming the current localefor the category. You can use this value as the second argument in asubsequent call to setlocale().

If no second argument is provided and the category is LC_ALL, theresult is implementation-dependent. It may be a string ofconcatenated locale names (separator also implementation-dependent)or a single locale name. Please consult your setlocale(3) man page fordetails.

If a second argument is given and it corresponds to a valid locale,the locale for the category is set to that value, and the functionreturns the now-current locale value. You can then use this in yetanother call to setlocale(). (In some implementations, the returnvalue may sometimes differ from the value you gave as the secondargument--think of it as an alias for the value you gave.)

As the example shows, if the second argument is an empty string, thecategory's locale is returned to the default specified by thecorresponding environment variables. Generally, this results in areturn to the default that was in force when Perl started up: changesto the environment made by the application after startup may or may notbe noticed, depending on your system's C library.

If the second argument does not correspond to a valid locale, the localefor the category is not changed, and the function returns undef.

Note that Perl ignores the current LC_CTYPE and LC_COLLATE localeswithin the scope of a use locale ':not_characters'.

For further information about the categories, consult setlocale(3).

Finding locales

For locales available in your system, consult also setlocale(3) tosee whether it leads to the list of available locales (search for theSEE ALSO section). If that fails, try the following command lines:

  1. locale -a
  2. nlsinfo
  3. ls /usr/lib/nls/loc
  4. ls /usr/lib/locale
  5. ls /usr/lib/nls
  6. ls /usr/share/locale

and see whether they list something resembling these

  1. en_US.ISO8859-1 de_DE.ISO8859-1 ru_RU.ISO8859-5
  2. en_US.iso88591 de_DE.iso88591 ru_RU.iso88595
  3. en_US de_DE ru_RU
  4. en de ru
  5. english german russian
  6. english.iso88591 german.iso88591 russian.iso88595
  7. english.roman8 russian.koi8r

Sadly, even though the calling interface for setlocale() has beenstandardized, names of locales and the directories where theconfiguration resides have not been. The basic form of the name islanguage_territory.codeset, but the latter parts afterlanguage are not always present. The language and countryare usually from the standards ISO 3166 and ISO 639, thetwo-letter abbreviations for the countries and the languages of theworld, respectively. The codeset part often mentions some ISO8859 character set, the Latin codesets. For example, ISO 8859-1is the so-called "Western European codeset" that can be used to encodemost Western European languages adequately. Again, there are severalways to write even the name of that one standard. Lamentably.

Two special locales are worth particular mention: "C" and "POSIX".Currently these are effectively the same locale: the difference ismainly that the first one is defined by the C standard, the second bythe POSIX standard. They define the default locale in whichevery program starts in the absence of locale information in itsenvironment. (The default default locale, if you will.) Its languageis (American) English and its character codeset ASCII.Warning. The C locale delivered by some vendors may notactually exactly match what the C standard calls for. So beware.

NOTE: Not all systems have the "POSIX" locale (not all systems arePOSIX-conformant), so use "C" when you need explicitly to specify thisdefault locale.

LOCALE PROBLEMS

You may encounter the following warning message at Perl startup:

  1. perl: warning: Setting locale failed.
  2. perl: warning: Please check that your locale settings:
  3. LC_ALL = "En_US",
  4. LANG = (unset)
  5. are supported and installed on your system.
  6. perl: warning: Falling back to the standard locale ("C").

This means that your locale settings had LC_ALL set to "En_US" andLANG exists but has no value. Perl tried to believe you but could not.Instead, Perl gave up and fell back to the "C" locale, the default localethat is supposed to work no matter what. This usually means your localesettings were wrong, they mention locales your system has never heardof, or the locale installation in your system has problems (for example,some system files are broken or missing). There are quick and temporaryfixes to these problems, as well as more thorough and lasting fixes.

Temporarily fixing locale problems

The two quickest fixes are either to render Perl silent about anylocale inconsistencies or to run Perl under the default locale "C".

Perl's moaning about locale problems can be silenced by setting theenvironment variable PERL_BADLANG to a zero value, for example "0".This method really just sweeps the problem under the carpet: you tellPerl to shut up even when Perl sees that something is wrong. Do notbe surprised if later something locale-dependent misbehaves.

Perl can be run under the "C" locale by setting the environmentvariable LC_ALL to "C". This method is perhaps a bit more civilizedthan the PERL_BADLANG approach, but setting LC_ALL (orother locale variables) may affect other programs as well, not justPerl. In particular, external programs run from within Perl will seethese changes. If you make the new settings permanent (read on), allprograms you run see the changes. See ENVIRONMENT forthe full list of relevant environment variables and USING LOCALESfor their effects in Perl. Effects in other programs areeasily deducible. For example, the variable LC_COLLATE may well affectyour sort program (or whatever the program that arranges "records"alphabetically in your system is called).

You can test out changing these variables temporarily, and if thenew settings seem to help, put those settings into your shell startupfiles. Consult your local documentation for the exact details. For inBourne-like shells (sh, ksh, bash, zsh):

  1. LC_ALL=en_US.ISO8859-1
  2. export LC_ALL

This assumes that we saw the locale "en_US.ISO8859-1" using the commandsdiscussed above. We decided to try that instead of the above faultylocale "En_US"--and in Cshish shells (csh, tcsh)

  1. setenv LC_ALL en_US.ISO8859-1

or if you have the "env" application you can do in any shell

  1. env LC_ALL=en_US.ISO8859-1 perl ...

If you do not know what shell you have, consult your localhelpdesk or the equivalent.

Permanently fixing locale problems

The slower but superior fixes are when you may be able to yourselffix the misconfiguration of your own environment variables. Themis(sing)configuration of the whole system's locales usually requiresthe help of your friendly system administrator.

First, see earlier in this document about Finding locales. That tellshow to find which locales are really supported--and more importantly,installed--on your system. In our example error message, environmentvariables affecting the locale are listed in the order of decreasingimportance (and unset variables do not matter). Therefore, havingLC_ALL set to "En_US" must have been the bad choice, as shown by theerror message. First try fixing locale settings listed first.

Second, if using the listed commands you see something exactly(prefix matches do not count and case usually counts) like "En_US"without the quotes, then you should be okay because you are using alocale name that should be installed and available in your system.In this case, see Permanently fixing your system's locale configuration.

Permanently fixing your system's locale configuration

This is when you see something like:

  1. perl: warning: Please check that your locale settings:
  2. LC_ALL = "En_US",
  3. LANG = (unset)
  4. are supported and installed on your system.

but then cannot see that "En_US" listed by the above-mentionedcommands. You may see things like "en_US.ISO8859-1", but that isn'tthe same. In this case, try running under a localethat you can list and which somehow matches what you tried. Therules for matching locale names are a bit vague becausestandardization is weak in this area. See again theFinding locales about general rules.

Fixing system locale configuration

Contact a system administrator (preferably your own) and report the exacterror message you get, and ask them to read this same documentation youare now reading. They should be able to check whether there is somethingwrong with the locale configuration of the system. The Finding localessection is unfortunately a bit vague about the exact commands and placesbecause these things are not that standardized.

The localeconv function

The POSIX::localeconv() function allows you to get particulars of thelocale-dependent numeric formatting information specified by the currentLC_NUMERIC and LC_MONETARY locales. (If you just want the name ofthe current locale for a particular category, use POSIX::setlocale()with a single parameter--see The setlocale function.)

  1. use POSIX qw(locale_h);
  2. # Get a reference to a hash of locale-dependent info
  3. $locale_values = localeconv();
  4. # Output sorted list of the values
  5. for (sort keys %$locale_values) {
  6. printf "%-20s = %s\n", $_, $locale_values->{$_}
  7. }

localeconv() takes no arguments, and returns a reference to a hash.The keys of this hash are variable names for formatting, such asdecimal_point and thousands_sep. The values are thecorresponding, er, values. See localeconv in POSIX for a longerexample listing the categories an implementation might be expected toprovide; some provide more and others fewer. You don't need anexplicit use locale, because localeconv() always observes thecurrent locale.

Here's a simple-minded example program that rewrites its command-lineparameters as integers correctly formatted in the current locale:

  1. # See comments in previous example
  2. require 5.004;
  3. use POSIX qw(locale_h);
  4. # Get some of locale's numeric formatting parameters
  5. my ($thousands_sep, $grouping) =
  6. @{localeconv()}{'thousands_sep', 'grouping'};
  7. # Apply defaults if values are missing
  8. $thousands_sep = ',' unless $thousands_sep;
  9. # grouping and mon_grouping are packed lists
  10. # of small integers (characters) telling the
  11. # grouping (thousand_seps and mon_thousand_seps
  12. # being the group dividers) of numbers and
  13. # monetary quantities. The integers' meanings:
  14. # 255 means no more grouping, 0 means repeat
  15. # the previous grouping, 1-254 means use that
  16. # as the current grouping. Grouping goes from
  17. # right to left (low to high digits). In the
  18. # below we cheat slightly by never using anything
  19. # else than the first grouping (whatever that is).
  20. if ($grouping) {
  21. @grouping = unpack("C*", $grouping);
  22. } else {
  23. @grouping = (3);
  24. }
  25. # Format command line params for current locale
  26. for (@ARGV) {
  27. $_ = int; # Chop non-integer part
  28. 1 while
  29. s/(\d)(\d{$grouping[0]}($|$thousands_sep))/$1$thousands_sep$2/;
  30. print "$_";
  31. }
  32. print "\n";

I18N::Langinfo

Another interface for querying locale-dependent information is theI18N::Langinfo::langinfo() function, available at least in Unix-likesystems and VMS.

The following example will import the langinfo() function itself andthree constants to be used as arguments to langinfo(): a constant forthe abbreviated first day of the week (the numbering starts fromSunday = 1) and two more constants for the affirmative and negativeanswers for a yes/no question in the current locale.

  1. use I18N::Langinfo qw(langinfo ABDAY_1 YESSTR NOSTR);
  2. my ($abday_1, $yesstr, $nostr)
  3. = map { langinfo } qw(ABDAY_1 YESSTR NOSTR);
  4. print "$abday_1? [$yesstr/$nostr] ";

In other words, in the "C" (or English) locale the above will probablyprint something like:

  1. Sun? [yes/no]

See I18N::Langinfo for more information.

LOCALE CATEGORIES

The following subsections describe basic locale categories. Beyond these,some combination categories allow manipulation of more than onebasic category at a time. See ENVIRONMENT for a discussion of these.

Category LC_COLLATE: Collation

In the scope of use locale (but not ause locale ':not_characters'), Perl looks to the LC_COLLATEenvironment variable to determine the application's notions on collation(ordering) of characters. For example, "b" follows "a" in Latinalphabets, but where do "á" and "å" belong? And while"color" follows "chocolate" in English, what about in Spanish?

The following collations all make sense and you may meet any of themif you "use locale".

  1. A B C D E a b c d e
  2. A a B b C c D d E e
  3. a A b B c C d D e E
  4. a b c d e A B C D E

Here is a code snippet to tell what "word"characters are in the current locale, in that locale's order:

  1. use locale;
  2. print +(sort grep /\w/, map { chr } 0..255), "\n";

Compare this with the characters that you see and their order if youstate explicitly that the locale should be ignored:

  1. no locale;
  2. print +(sort grep /\w/, map { chr } 0..255), "\n";

This machine-native collation (which is what you get unless uselocale has appeared earlier in the same block) must be used forsorting raw binary data, whereas the locale-dependent collation of thefirst example is useful for natural text.

As noted in USING LOCALES, cmp compares according to the currentcollation locale when use locale is in effect, but falls back to achar-by-char comparison for strings that the locale says are equal. Youcan use POSIX::strcoll() if you don't want this fall-back:

  1. use POSIX qw(strcoll);
  2. $equal_in_locale =
  3. !strcoll("space and case ignored", "SpaceAndCaseIgnored");

$equal_in_locale will be true if the collation locale specifies adictionary-like ordering that ignores space characters completely andwhich folds case.

If you have a single string that you want to check for "equality inlocale" against several others, you might think you could gain a littleefficiency by using POSIX::strxfrm() in conjunction with eq:

  1. use POSIX qw(strxfrm);
  2. $xfrm_string = strxfrm("Mixed-case string");
  3. print "locale collation ignores spaces\n"
  4. if $xfrm_string eq strxfrm("Mixed-casestring");
  5. print "locale collation ignores hyphens\n"
  6. if $xfrm_string eq strxfrm("Mixedcase string");
  7. print "locale collation ignores case\n"
  8. if $xfrm_string eq strxfrm("mixed-case string");

strxfrm() takes a string and maps it into a transformed string for usein char-by-char comparisons against other transformed strings duringcollation. "Under the hood", locale-affected Perl comparison operatorscall strxfrm() for both operands, then do a char-by-charcomparison of the transformed strings. By calling strxfrm() explicitlyand using a non locale-affected comparison, the example attempts to savea couple of transformations. But in fact, it doesn't save anything: Perlmagic (see Magic Variables in perlguts) creates the transformed version of astring the first time it's needed in a comparison, then keeps this version aroundin case it's needed again. An example rewritten the easy way withcmp runs just about as fast. It also copes with null charactersembedded in strings; if you call strxfrm() directly, it treats the firstnull it finds as a terminator. don't expect the transformed stringsit produces to be portable across systems--or even from one revisionof your operating system to the next. In short, don't call strxfrm()directly: let Perl do it for you.

Note: use locale isn't shown in some of these examples because it isn'tneeded: strcoll() and strxfrm() exist only to generate locale-dependentresults, and so always obey the current LC_COLLATE locale.

Category LC_CTYPE: Character Types

In the scope of use locale (but not ause locale ':not_characters'), Perl obeys the LC_CTYPE localesetting. This controls the application's notion of which characters arealphabetic. This affects Perl's \w regular expression metanotation,which stands for alphanumeric characters--that is, alphabetic,numeric, and including other special characters such as the underscore orhyphen. (Consult perlre for more information aboutregular expressions.) Thanks to LC_CTYPE, depending on your localesetting, characters like "æ", "ð", "ß", and"ø" may be understood as \w characters.

The LC_CTYPE locale also provides the map used in transliteratingcharacters between lower and uppercase. This affects the case-mappingfunctions--lc(), lcfirst, uc(), and ucfirst(); case-mappinginterpolation with \l, \L, \u, or \U in double-quoted stringsand s/// substitutions; and case-independent regular expressionpattern matching using the i modifier.

Finally, LC_CTYPE affects the POSIX character-class testfunctions--isalpha(), islower(), and so on. For example, if you movefrom the "C" locale to a 7-bit Scandinavian one, you may find--possiblyto your surprise--that "|" moves from the ispunct() class to isalpha().Unfortunately, this creates big problems for regular expressions. "|" stillmeans alternation even though it matches \w.

Note: A broken or malicious LC_CTYPE locale definition may resultin clearly ineligible characters being considered to be alphanumeric byyour application. For strict matching of (mundane) ASCII letters anddigits--for example, in command strings--locale-aware applicationsshould use \w with the /a regular expression modifier. See SECURITY.

Category LC_NUMERIC: Numeric Formatting

After a proper POSIX::setlocale() call, Perl obeys the LC_NUMERIClocale information, which controls an application's idea of how numbersshould be formatted for human readability by the printf(), sprintf(), andwrite() functions. String-to-numeric conversion by the POSIX::strtod()function is also affected. In most implementations the only effect is tochange the character used for the decimal point--perhaps from "." to ",".These functions aren't aware of such niceties as thousands separation andso on. (See The localeconv function if you care about these things.)

Output produced by print() is also affected by the current locale: itcorresponds to what you'd get from printf() in the "C" locale. Thesame is true for Perl's internal conversions between numeric andstring formats:

  1. use POSIX qw(strtod setlocale LC_NUMERIC);
  2. setlocale LC_NUMERIC, "";
  3. $n = 5/2; # Assign numeric 2.5 to $n
  4. $a = " $n"; # Locale-dependent conversion to string
  5. print "half five is $n\n"; # Locale-dependent output
  6. printf "half five is %g\n", $n; # Locale-dependent output
  7. print "DECIMAL POINT IS COMMA\n"
  8. if $n == (strtod("2,5"))[0]; # Locale-dependent conversion

See also I18N::Langinfo and RADIXCHAR.

Category LC_MONETARY: Formatting of monetary amounts

The C standard defines the LC_MONETARY category, but not a functionthat is affected by its contents. (Those with experience of standardscommittees will recognize that the working group decided to punt on theissue.) Consequently, Perl takes no notice of it. If you really wantto use LC_MONETARY, you can query its contents--seeThe localeconv function--and use the information that it returns in yourapplication's own formatting of currency amounts. However, you may wellfind that the information, voluminous and complex though it may be, stilldoes not quite meet your requirements: currency formatting is a hard nutto crack.

See also I18N::Langinfo and CRNCYSTR.

LC_TIME

Output produced by POSIX::strftime(), which builds a formattedhuman-readable date/time string, is affected by the current LC_TIMElocale. Thus, in a French locale, the output produced by the %Bformat element (full month name) for the first month of the year wouldbe "janvier". Here's how to get a list of long month names in thecurrent locale:

  1. use POSIX qw(strftime);
  2. for (0..11) {
  3. $long_month_name[$_] =
  4. strftime("%B", 0, 0, 0, 1, $_, 96);
  5. }

Note: use locale isn't needed in this example: as a function thatexists only to generate locale-dependent results, strftime() alwaysobeys the current LC_TIME locale.

See also I18N::Langinfo and ABDAY_1..ABDAY_7, DAY_1..DAY_7,ABMON_1..ABMON_12, and ABMON_1..ABMON_12.

Other categories

The remaining locale category, LC_MESSAGES (possibly supplementedby others in particular implementations) is not currently used byPerl--except possibly to affect the behavior of library functionscalled by extensions outside the standard Perl distribution and by theoperating system and its utilities. Note especially that the stringvalue of $! and the error messages given by external utilities maybe changed by LC_MESSAGES. If you want to have portable errorcodes, use %!. See Errno.

SECURITY

Although the main discussion of Perl security issues can be found inperlsec, a discussion of Perl's locale handling would be incompleteif it did not draw your attention to locale-dependent security issues.Locales--particularly on systems that allow unprivileged users tobuild their own locales--are untrustworthy. A malicious (or just plainbroken) locale can make a locale-aware application give unexpectedresults. Here are a few possibilities:

  • Regular expression checks for safe file names or mail addresses using\w may be spoofed by an LC_CTYPE locale that claims thatcharacters such as ">" and "|" are alphanumeric.

  • String interpolation with case-mapping, as in, say, $dest ="C:\U$name.$ext", may produce dangerous results if a bogus LC_CTYPEcase-mapping table is in effect.

  • A sneaky LC_COLLATE locale could result in the names of students with"D" grades appearing ahead of those with "A"s.

  • An application that takes the trouble to use information inLC_MONETARY may format debits as if they were credits and vice versaif that locale has been subverted. Or it might make payments in USdollars instead of Hong Kong dollars.

  • The date and day names in dates formatted by strftime() could bemanipulated to advantage by a malicious user able to subvert theLC_DATE locale. ("Look--it says I wasn't in the building onSunday.")

Such dangers are not peculiar to the locale system: any aspect of anapplication's environment which may be modified maliciously presentssimilar challenges. Similarly, they are not specific to Perl: anyprogramming language that allows you to write programs that takeaccount of their environment exposes you to these issues.

Perl cannot protect you from all possibilities shown in theexamples--there is no substitute for your own vigilance--but, whenuse locale is in effect, Perl uses the tainting mechanism (seeperlsec) to mark string results that become locale-dependent, andwhich may be untrustworthy in consequence. Here is a summary of thetainting behavior of operators and functions that may be affected bythe locale:

  • Comparison operators (lt, le, ge, gt and cmp):

    Scalar true/false (or less/equal/greater) result is never tainted.

  • Case-mapping interpolation (with \l, \L, \u or \U)

    Result string containing interpolated material is tainted ifuse locale (but not use locale ':not_characters') is in effect.

  • Matching operator (m//):

    Scalar true/false result never tainted.

    Subpatterns, either delivered as a list-context result or as $1 etc.are tainted if use locale (but not use locale ':not_characters')is in effect, and the subpattern regularexpression contains \w (to match an alphanumeric character), \W(non-alphanumeric character), \s (whitespace character), or \S(non whitespace character). The matched-pattern variable, $&, $`(pre-match), $' (post-match), and $+ (last match) are also tainted ifuse locale is in effect and the regular expression contains \w,\W, \s, or \S.

  • Substitution operator (s///):

    Has the same behavior as the match operator. Also, the leftoperand of =~ becomes tainted when use locale(but not use locale ':not_characters') is in effect if modified asa result of a substitution based on a regularexpression match involving \w, \W, \s, or \S; or ofcase-mapping with \l, \L,\u or \U.

  • Output formatting functions (printf() and write()):

    Results are never tainted because otherwise even output from print,for example print(1/7), should be tainted if use locale is ineffect.

  • Case-mapping functions (lc(), lcfirst(), uc(), ucfirst()):

    Results are tainted if use locale (but notuse locale ':not_characters') is in effect.

  • POSIX locale-dependent functions (localeconv(), strcoll(),strftime(), strxfrm()):

    Results are never tainted.

  • POSIX character class tests (isalnum(), isalpha(), isdigit(),isgraph(), islower(), isprint(), ispunct(), isspace(), isupper(),isxdigit()):

    True/false results are never tainted.

Three examples illustrate locale-dependent tainting.The first program, which ignores its locale, won't run: a value takendirectly from the command line may not be used to name an output filewhen taint checks are enabled.

  1. #/usr/local/bin/perl -T
  2. # Run with taint checking
  3. # Command line sanity check omitted...
  4. $tainted_output_file = shift;
  5. open(F, ">$tainted_output_file")
  6. or warn "Open of $untainted_output_file failed: $!\n";

The program can be made to run by "laundering" the tainted value througha regular expression: the second example--which still ignores localeinformation--runs, creating the file named on its command lineif it can.

  1. #/usr/local/bin/perl -T
  2. $tainted_output_file = shift;
  3. $tainted_output_file =~ m%[\w/]+%;
  4. $untainted_output_file = $&;
  5. open(F, ">$untainted_output_file")
  6. or warn "Open of $untainted_output_file failed: $!\n";

Compare this with a similar but locale-aware program:

  1. #/usr/local/bin/perl -T
  2. $tainted_output_file = shift;
  3. use locale;
  4. $tainted_output_file =~ m%[\w/]+%;
  5. $localized_output_file = $&;
  6. open(F, ">$localized_output_file")
  7. or warn "Open of $localized_output_file failed: $!\n";

This third program fails to run because $& is tainted: it is the resultof a match involving \w while use locale is in effect.

ENVIRONMENT

  • PERL_BADLANG

    A string that can suppress Perl's warning about failed locale settingsat startup. Failure can occur if the locale support in the operatingsystem is lacking (broken) in some way--or if you mistyped the name ofa locale when you set up your environment. If this environmentvariable is absent, or has a value that does not evaluate to integerzero--that is, "0" or ""-- Perl will complain about locale settingfailures.

    NOTE: PERL_BADLANG only gives you a way to hide the warning message.The message tells about some problem in your system's locale support,and you should investigate what the problem is.

The following environment variables are not specific to Perl: They arepart of the standardized (ISO C, XPG4, POSIX 1.c) setlocale() methodfor controlling an application's opinion on data.

  • LC_ALL

    LC_ALL is the "override-all" locale environment variable. Ifset, it overrides all the rest of the locale environment variables.

  • LANGUAGE

    NOTE: LANGUAGE is a GNU extension, it affects you only if youare using the GNU libc. This is the case if you are using e.g. Linux.If you are using "commercial" Unixes you are most probably notusing GNU libc and you can ignore LANGUAGE.

    However, in the case you are using LANGUAGE: it affects thelanguage of informational, warning, and error messages output bycommands (in other words, it's like LC_MESSAGES) but it has higherpriority than LC_ALL. Moreover, it's not a single value butinstead a "path" (":"-separated list) of languages (not locales).See the GNU gettext library documentation for more information.

  • LC_CTYPE

    In the absence of LC_ALL, LC_CTYPE chooses the character typelocale. In the absence of both LC_ALL and LC_CTYPE, LANGchooses the character type locale.

  • LC_COLLATE

    In the absence of LC_ALL, LC_COLLATE chooses the collation(sorting) locale. In the absence of both LC_ALL and LC_COLLATE,LANG chooses the collation locale.

  • LC_MONETARY

    In the absence of LC_ALL, LC_MONETARY chooses the monetaryformatting locale. In the absence of both LC_ALL and LC_MONETARY,LANG chooses the monetary formatting locale.

  • LC_NUMERIC

    In the absence of LC_ALL, LC_NUMERIC chooses the numeric formatlocale. In the absence of both LC_ALL and LC_NUMERIC, LANGchooses the numeric format.

  • LC_TIME

    In the absence of LC_ALL, LC_TIME chooses the date and timeformatting locale. In the absence of both LC_ALL and LC_TIME,LANG chooses the date and time formatting locale.

  • LANG

    LANG is the "catch-all" locale environment variable. If it is set, itis used as the last resort after the overall LC_ALL and thecategory-specific LC_....

Examples

The LC_NUMERIC controls the numeric output:

  1. use locale;
  2. use POSIX qw(locale_h); # Imports setlocale() and the LC_ constants.
  3. setlocale(LC_NUMERIC, "fr_FR") or die "Pardon";
  4. printf "%g\n", 1.23; # If the "fr_FR" succeeded, probably shows 1,23.

and also how strings are parsed by POSIX::strtod() as numbers:

  1. use locale;
  2. use POSIX qw(locale_h strtod);
  3. setlocale(LC_NUMERIC, "de_DE") or die "Entschuldigung";
  4. my $x = strtod("2,34") + 5;
  5. print $x, "\n"; # Probably shows 7,34.

NOTES

Backward compatibility

Versions of Perl prior to 5.004 mostly ignored locale information,generally behaving as if something similar to the "C" locale werealways in force, even if the program environment suggested otherwise(see The setlocale function). By default, Perl still behaves thisway for backward compatibility. If you want a Perl application to payattention to locale information, you must use the use localepragma (see The use locale pragma) or, in the unlikely eventthat you want to do so for just pattern matching, the/l regular expression modifier (see Character set modifiers in perlre) to instruct it to do so.

Versions of Perl from 5.002 to 5.003 did use the LC_CTYPEinformation if available; that is, \w did understand whatwere the letters according to the locale environment variables.The problem was that the user had no control over the feature:if the C library supported locales, Perl used them.

I18N:Collate obsolete

In versions of Perl prior to 5.004, per-locale collation was possibleusing the I18N::Collate library module. This module is now mildlyobsolete and should be avoided in new applications. The LC_COLLATEfunctionality is now integrated into the Perl core language: One canuse locale-specific scalar data completely normally with use locale,so there is no longer any need to juggle with the scalar references ofI18N::Collate.

Sort speed and memory use impacts

Comparing and sorting by locale is usually slower than the defaultsorting; slow-downs of two to four times have been observed. It willalso consume more memory: once a Perl scalar variable has participatedin any string comparison or sorting operation obeying the localecollation rules, it will take 3-15 times more memory than before. (Theexact multiplier depends on the string's contents, the operating systemand the locale.) These downsides are dictated more by the operatingsystem's implementation of the locale system than by Perl.

write() and LC_NUMERIC

If a program's environment specifies an LC_NUMERIC locale and uselocale is in effect when the format is declared, the locale is usedto specify the decimal point character in formatted output. Formattedoutput cannot be controlled by use locale at the time when write()is called.

Freely available locale definitions

The Unicode CLDR project extracts the POSIX portion of many of itslocales, available at

  1. http://unicode.org/Public/cldr/latest/

There is a large collection of locale definitions at:

  1. http://std.dkuug.dk/i18n/WG15-collection/locales/

You should be aware that it isunsupported, and is not claimed to be fit for any purpose. If yoursystem allows installation of arbitrary locales, you may find thedefinitions useful as they are, or as a basis for the development ofyour own locales.

I18n and l10n

"Internationalization" is often abbreviated as i18n because its firstand last letters are separated by eighteen others. (You may guess whythe internalin ... internaliti ... i18n tends to get abbreviated.) Inthe same way, "localization" is often abbreviated to l10n.

An imperfect standard

Internationalization, as defined in the C and POSIX standards, can becriticized as incomplete, ungainly, and having too large a granularity.(Locales apply to a whole process, when it would arguably be more usefulto have them apply to a single thread, window group, or whatever.) Theyalso have a tendency, like standards groups, to divide the world intonations, when we all know that the world can equally well be dividedinto bankers, bikers, gamers, and so on.

Unicode and UTF-8

The support of Unicode is new starting from Perl version v5.6, and more fullyimplemented in version v5.8 and later. See perluniintro. It isstrongly recommended that when combining Unicode and locale (starting inv5.16), you use

  1. use locale ':not_characters';

When this form of the pragma is used, only the non-character portions oflocales are used by Perl, for example LC_NUMERIC. Perl assumes thatyou have translated all the characters it is to operate on into Unicode(actually the platform's native character set (ASCII or EBCDIC) plusUnicode). For data in files, this can conveniently be done by alsospecifying

  1. use open ':locale';

This pragma arranges for all inputs from files to be translated intoUnicode from the current locale as specified in the environment (seeENVIRONMENT), and all outputs to files to be translated backinto the locale. (See open). On a per-filehandle basis, you caninstead use the PerlIO::locale module, or the Encode::Localemodule, both available from CPAN. The latter module also has methods toease the handling of ARGV and environment variables, and can be usedon individual strings. Also, if you know that all your locales will beUTF-8, as many are these days, you can use the -Ccommand line switch.

This form of the pragma allows essentially seamless handling of localeswith Unicode. The collation order will be Unicode's. It is stronglyrecommended that when you need to order and sort strings that you usethe standard module Unicode::Collate which gives much better resultsin many instances than you can get with the old-style locale handling.

For pre-v5.16 Perls, or if you use the locale pragma without the:not_characters parameter, Perl tries to work with both Unicode andlocales--but there are problems.

Perl does not handle multi-byte locales in this case, such as have beenused for variousAsian languages, such as Big5 or Shift JIS. However, the increasinglycommon multi-byte UTF-8 locales, if properly implemented, may workreasonably well (depending on your C library implementation) in thisform of the locale pragma, simply because boththey and Perl store characters that take up multiple bytes the same way.However, some, if not most, C library implementations may not processthe characters in the upper half of the Latin-1 range (128 - 255)properly under LC_CTYPE. To see if a character is a particular typeunder a locale, Perl uses the functions like isalnum(). Your Clibrary may not work for UTF-8 locales with those functions, insteadonly working under the newer wide library functions like iswalnum().

Perl generally takes the tack to use locale rules on code points that can fitin a single byte, and Unicode rules for those that can't (though thisisn't uniformly applied, see the note at the end of this section). Thisprevents many problems in locales that aren't UTF-8. Suppose the localeis ISO8859-7, Greek. The character at 0xD7 there is a capital Chi. Butin the ISO8859-1 locale, Latin1, it is a multiplication sign. The POSIXregular expression character class [[:alpha:]] will magically match0xD7 in the Greek locale but not in the Latin one.

However, there are places where this breaks down. Certain constructs arefor Unicode only, such as \p{Alpha}. They assume that 0xD7 always has itsUnicode meaning (or the equivalent on EBCDIC platforms). Since Latin1 is asubset of Unicode and 0xD7 is the multiplication sign in both Latin1 andUnicode, \p{Alpha} will never match it, regardless of locale. A similarissue occurs with \N{...}. It is therefore a bad idea to use \p{} or\N{} under plain use locale--unless you can guarantee that thelocale will be a ISO8859-1. Use POSIX character classes instead.

Another problem with this approach is that operations that cross thesingle byte/multiple byte boundary are not well-defined, and so aredisallowed. (This boundary is between the codepoints at 255/256.).For example, lower casing LATIN CAPITAL LETTER Y WITH DIAERESIS (U+0178)should return LATIN SMALL LETTER Y WITH DIAERESIS (U+00FF). But in theGreek locale, for example, there is no character at 0xFF, and Perlhas no way of knowing what the character at 0xFF is really supposed torepresent. Thus it disallows the operation. In this mode, thelowercase of U+0178 is itself.

The same problems ensue if you enable automatic UTF-8-ification of yourstandard file handles, default open() layer, and @ARGV on non-ISO8859-1,non-UTF-8 locales (by using either the -C command line switch or thePERL_UNICODE environment variable; see perlrun).Things are read in as UTF-8, which would normally imply a Unicodeinterpretation, but the presence of a locale causes them to be interpretedin that locale instead. For example, a 0xD7 code point in the Unicodeinput, which should mean the multiplication sign, won't be interpreted byPerl that way under the Greek locale. This is not a problemprovided you make certain that all locales will always and only be eitheran ISO8859-1, or, if you don't have a deficient C library, a UTF-8 locale.

Vendor locales are notoriously buggy, and it is difficult for Perl to testits locale-handling code because this interacts with code that Perl has nocontrol over; therefore the locale-handling code in Perl may be buggy aswell. (However, the Unicode-supplied locales should be better, andthere is a feed back mechanism to correct any problems. SeeFreely available locale definitions.)

If you have Perl v5.16, the problems mentioned above go away if you usethe :not_characters parameter to the locale pragma (except for vendorbugs in the non-character portions). If you don't have v5.16, and youdo have locales that work, using them may be worthwhile for certainspecific purposes, as long as you keep in mind the gotchas alreadymentioned. For example, if the collation for your locales works, itruns faster under locales than under Unicode::Collate; and you gainaccess to such things as the local currency symbol and the names of themonths and days of the week. (But to hammer home the point, in v5.16,you get this access without the downsides of locales by using the:not_characters form of the pragma.)

Note: The policy of using locale rules for code points that can fit in abyte, and Unicode rules for those that can't is not uniformly applied.Pre-v5.12, it was somewhat haphazard; in v5.12 it was applied fairlyconsistently to regular expression matching except for bracketedcharacter classes; in v5.14 it was extended to all regex matches; and inv5.16 to the casing operations such as "\L" and uc(). Forcollation, in all releases, the system's strxfrm() function is called,and whatever it does is what you get.

BUGS

Broken systems

In certain systems, the operating system's locale supportis broken and cannot be fixed or used by Perl. Such deficiencies canand will result in mysterious hangs and/or Perl core dumps whenuse locale is in effect. When confronted with such a system,please report in excruciating detail to <[email protected]>, andalso contact your vendor: bug fixes may exist for these problemsin your operating system. Sometimes such bug fixes are called anoperating system upgrade.

SEE ALSO

I18N::Langinfo, perluniintro, perlunicode, open,isalnum in POSIX, isalpha in POSIX,isdigit in POSIX, isgraph in POSIX, islower in POSIX,isprint in POSIX, ispunct in POSIX, isspace in POSIX,isupper in POSIX, isxdigit in POSIX, localeconv in POSIX,setlocale in POSIX, strcoll in POSIX, strftime in POSIX,strtod in POSIX, strxfrm in POSIX.

HISTORY

Jarkko Hietaniemi's original perli18n.pod heavily hacked by DominicDunlop, assisted by the perl5-porters. Prose worked over a bit byTom Christiansen, and updated by Perl 5 porters.

 
Source : perldoc.perl.org - Official documentation for the Perl programming language
Site maintained by Jon Allen (JJ)     See the project page for more details
Documentation maintained by the Perl 5 Porters
(Sebelumnya) Writing portable PerlPerl Unicode introduction (Berikutnya)