You are viewing the version of this documentation from Perl 5.39.3. This is a development version of Perl.

CONTENTS

NAME

Unicode::Collate - Unicode Collation Algorithm

SYNOPSIS

use Unicode::Collate;

#construct
$Collator = Unicode::Collate->new(%tailoring);

#sort
@sorted = $Collator->sort(@not_sorted);

#compare
$result = $Collator->cmp($a, $b); # returns 1, 0, or -1.

Note: Strings in @not_sorted, $a and $b are interpreted according to Perl's Unicode support. See perlunicode, perluniintro, perlunitut, perlunifaq, utf8. Otherwise you can use preprocess or should decode them before.

DESCRIPTION

This module is an implementation of Unicode Technical Standard #10 (a.k.a. UTS #10) - Unicode Collation Algorithm (a.k.a. UCA).

Constructor and Tailoring

The new method returns a collator object. If new() is called with no parameters, the collator should do the default collation.

$Collator = Unicode::Collate->new(
   UCA_Version => $UCA_Version,
   alternate => $alternate, # alias for 'variable'
   backwards => $levelNumber, # or \@levelNumbers
   entry => $element,
   hangul_terminator => $term_primary_weight,
   highestFFFF => $bool,
   identical => $bool,
   ignoreName => qr/$ignoreName/,
   ignoreChar => qr/$ignoreChar/,
   ignore_level2 => $bool,
   katakana_before_hiragana => $bool,
   level => $collationLevel,
   long_contraction => $bool,
   minimalFFFE => $bool,
   normalization  => $normalization_form,
   overrideCJK => \&overrideCJK,
   overrideHangul => \&overrideHangul,
   preprocess => \&preprocess,
   rearrange => \@charList,
   rewrite => \&rewrite,
   suppress => \@charList,
   table => $filename,
   undefName => qr/$undefName/,
   undefChar => qr/$undefChar/,
   upper_before_lower => $bool,
   variable => $variable,
);
UCA_Version

If the revision (previously "tracking version") number of UCA is given, behavior of that revision is emulated on collating. If omitted, the return value of UCA_Version() is used.

The following revisions are supported. The default is 43.

  UCA       Unicode Standard         DUCET (@version)
-------------------------------------------------------
   8              3.1                3.0.1 (3.0.1d9)
   9     3.1 with Corrigendum 3      3.1.1
  11             4.0.0
  14             4.1.0
  16             5.0.0
  18             5.1.0
  20             5.2.0
  22             6.0.0
  24             6.1.0
  26             6.2.0
  28             6.3.0
  30             7.0.0
  32             8.0.0
  34             9.0.0
  36            10.0.0
  38            11.0.0
  40            12.0.0
  41            12.1.0
  43            13.0.0

* See below for long_contraction with UCA_Version 22 and 24.

* Noncharacters (e.g. U+FFFF) are not ignored, and can be overridden since UCA_Version 22.

* Out-of-range codepoints (greater than U+10FFFF) are not ignored, and can be overridden since UCA_Version 22.

* Fully ignorable characters were ignored, and would not interrupt contractions with UCA_Version 9 and 11.

* Treatment of ignorables after variables and some behaviors were changed at UCA_Version 9.

* Characters regarded as CJK unified ideographs (cf. overrideCJK) depend on UCA_Version.

* Many hangul jamo are assigned at UCA_Version 20, that will affect hangul_terminator.

alternate

-- see 3.2.2 Alternate Weighting, version 8 of UTS #10

For backward compatibility, alternate (old name) can be used as an alias for variable.

backwards

-- see 3.4 Backward Accents, UTS #10.

backwards => $levelNumber or \@levelNumbers

Weights in reverse order; ex. level 2 (diacritic ordering) in French. If omitted (or $levelNumber is undef or \@levelNumbers is []), forwards at all the levels.

entry

-- see 5 Tailoring; 9.1 Allkeys File Format, UTS #10.

If the same character (or a sequence of characters) exists in the collation element table through table, mapping to collation elements is overridden. If it does not exist, the mapping is defined additionally.

entry => <<'ENTRY', # for DUCET v4.0.0 (allkeys-4.0.0.txt)
0063 0068 ; [.0E6A.0020.0002.0063] # ch
0043 0068 ; [.0E6A.0020.0007.0043] # Ch
0043 0048 ; [.0E6A.0020.0008.0043] # CH
006C 006C ; [.0F4C.0020.0002.006C] # ll
004C 006C ; [.0F4C.0020.0007.004C] # Ll
004C 004C ; [.0F4C.0020.0008.004C] # LL
00F1      ; [.0F7B.0020.0002.00F1] # n-tilde
006E 0303 ; [.0F7B.0020.0002.00F1] # n-tilde
00D1      ; [.0F7B.0020.0008.00D1] # N-tilde
004E 0303 ; [.0F7B.0020.0008.00D1] # N-tilde
ENTRY

entry => <<'ENTRY', # for DUCET v4.0.0 (allkeys-4.0.0.txt)
00E6 ; [.0E33.0020.0002.00E6][.0E8B.0020.0002.00E6] # ae ligature as <a><e>
00C6 ; [.0E33.0020.0008.00C6][.0E8B.0020.0008.00C6] # AE ligature as <A><E>
ENTRY

NOTE: The code point in the UCA file format (before ';') must be a Unicode code point (defined as hexadecimal), but not a native code point. So 0063 must always denote U+0063, but not a character of "\x63".

Weighting may vary depending on collation element table. So ensure the weights defined in entry will be consistent with those in the collation element table loaded via table.

In DUCET v4.0.0, primary weight of C is 0E60 and that of D is 0E6D. So setting primary weight of CH to 0E6A (as a value between 0E60 and 0E6D) makes ordering as C < CH < D. Exactly speaking DUCET already has some characters between C and D: small capital C (U+1D04) with primary weight 0E64, c-hook/C-hook (U+0188/U+0187) with 0E65, and c-curl (U+0255) with 0E69. Then primary weight 0E6A for CH makes CH ordered between c-curl and D.

hangul_terminator

-- see 7.1.4 Trailing Weights, UTS #10.

If a true value is given (non-zero but should be positive), it will be added as a terminator primary weight to the end of every standard Hangul syllable. Secondary and any higher weights for terminator are set to zero. If the value is false or hangul_terminator key does not exist, insertion of terminator weights will not be performed.

Boundaries of Hangul syllables are determined according to conjoining Jamo behavior in the Unicode Standard and HangulSyllableType.txt.

Implementation Note: (1) For expansion mapping (Unicode character mapped to a sequence of collation elements), a terminator will not be added between collation elements, even if Hangul syllable boundary exists there. Addition of terminator is restricted to the next position to the last collation element.

(2) Non-conjoining Hangul letters (Compatibility Jamo, halfwidth Jamo, and enclosed letters) are not automatically terminated with a terminator primary weight. These characters may need terminator included in a collation element table beforehand.

highestFFFF

-- see 2.4 Tailored noncharacter weights, UTS #35 (LDML) Part 5: Collation.

If the parameter is made true, U+FFFF has a highest primary weight. When a boolean of $coll->ge($str, "abc") and $coll->le($str, "abc\x{FFFF}") is true, it is expected that $str begins with "abc", or another primary equivalent. $str may be "abcd", "abc012", but should not include U+FFFF such as "abc\x{FFFF}xyz".

$coll->le($str, "abc\x{FFFF}") works like $coll->lt($str, "abd") almost, but the latter has a problem that you should know which letter is next to c. For a certain language where ch as the next letter, "abch" is greater than "abc\x{FFFF}", but less than "abd".

Note: This is equivalent to (entry => 'FFFF ; [.FFFE.0020.0005.FFFF]'). Any other character than U+FFFF can be tailored by entry.

identical

-- see A.3 Deterministic Comparison, UTS #10.

By default, strings whose weights are equal should be equal, even though their code points are not equal. Completely ignorable characters are ignored.

If the parameter is made true, a final, tie-breaking level is used. If no difference of weights is found after the comparison through all the level specified by level, the comparison with code points will be performed. For the tie-breaking comparison, the sort key has code points of the original string appended. Completely ignorable characters are not ignored.

If preprocess and/or normalization is applied, the code points of the string after them (in NFD by default) are used.

ignoreChar
ignoreName

-- see 3.6 Variable Weighting, UTS #10.

Makes the entry in the table completely ignorable; i.e. as if the weights were zero at all level.

Through ignoreChar, any character matching qr/$ignoreChar/ will be ignored. Through ignoreName, any character whose name (given in the table file as a comment) matches qr/$ignoreName/ will be ignored.

E.g. when 'a' and 'e' are ignorable, 'element' is equal to 'lament' (or 'lmnt').

ignore_level2

-- see 5.1 Parametric Tailoring, UTS #10.

By default, case-sensitive comparison (that is level 3 difference) won't ignore accents (that is level 2 difference).

If the parameter is made true, accents (and other primary ignorable characters) are ignored, even though cases are taken into account.

NOTE: level should be 3 or greater.

katakana_before_hiragana

-- see 7.2 Tertiary Weight Table, UTS #10.

By default, hiragana is before katakana. If the parameter is made true, this is reversed.

NOTE: This parameter simplemindedly assumes that any hiragana/katakana distinctions must occur in level 3, and their weights at level 3 must be same as those mentioned in 7.3.1, UTS #10. If you define your collation elements which violate this requirement, this parameter does not work validly.

level

-- see 4.3 Form Sort Key, UTS #10.

Set the maximum level. Any higher levels than the specified one are ignored.

Level 1: alphabetic ordering
Level 2: diacritic ordering
Level 3: case ordering
Level 4: tie-breaking (e.g. in the case when variable is 'shifted')

ex.level => 2,

If omitted, the maximum is the 4th.

NOTE: The DUCET includes weights over 0xFFFF at the 4th level. But this module only uses weights within 0xFFFF. When variable is 'blanked' or 'non-ignorable' (other than 'shifted' and 'shift-trimmed'), the level 4 may be unreliable.

See also identical.

long_contraction

-- see 3.8.2 Well-Formedness of the DUCET, 4.2 Produce Array, UTS #10.

If the parameter is made true, for a contraction with three or more characters (here nicknamed "long contraction"), initial substrings will be handled. For example, a contraction ABC, where A is a starter, and B and C are non-starters (character with non-zero combining character class), will be detected even if there is not AB as a contraction.

Default: Usually false. If UCA_Version is 22 or 24, and the value of long_contraction is not specified in new(), a true value is set implicitly. This is a workaround to pass Conformance Tests for Unicode 6.0.0 and 6.1.0.

change() handles long_contraction explicitly only. If long_contraction is not specified in change(), even though UCA_Version is changed, long_contraction will not be changed.

Limitation: Scanning non-starters is one-way (no back tracking). If AB is found but not ABC is not found, other long contraction where the first character is A and the second is not B may not be found.

Under (normalization => undef), detection step of discontiguous contractions will be skipped.

Note: The following contractions in DUCET are not considered in steps S2.1.1 to S2.1.3, where they are discontiguous.

0FB2 0F71 0F80 (TIBETAN VOWEL SIGN VOCALIC RR)
0FB3 0F71 0F80 (TIBETAN VOWEL SIGN VOCALIC LL)

For example TIBETAN VOWEL SIGN VOCALIC RR with COMBINING TILDE OVERLAY (U+0344) is 0FB2 0344 0F71 0F80 in NFD. In this case 0FB2 0F80 (TIBETAN VOWEL SIGN VOCALIC R) is detected, instead of 0FB2 0F71 0F80. Inserted 0344 makes 0FB2 0F71 0F80 discontiguous and lack of contraction 0FB2 0F71 prohibits 0FB2 0F71 0F80 from being detected.

minimalFFFE

-- see 1.1.1 U+FFFE, UTS #35 (LDML) Part 5: Collation.

If the parameter is made true, U+FFFE has a minimal primary weight. The comparison between "$a1\x{FFFE}$a2" and "$b1\x{FFFE}$b2" first compares $a1 and $b1 at level 1, and then $a2 and $b2 at level 1, as followed.

"ab\x{FFFE}a"
"Ab\x{FFFE}a"
"ab\x{FFFE}c"
"Ab\x{FFFE}c"
"ab\x{FFFE}xyz"
"abc\x{FFFE}def"
"abc\x{FFFE}xYz"
"aBc\x{FFFE}xyz"
"abcX\x{FFFE}def"
"abcx\x{FFFE}xyz"
"b\x{FFFE}aaa"
"bbb\x{FFFE}a"

Note: This is equivalent to (entry => 'FFFE ; [.0001.0020.0005.FFFE]'). Any other character than U+FFFE can be tailored by entry.

normalization

-- see 4.1 Normalize, UTS #10.

If specified, strings are normalized before preparation of sort keys (the normalization is executed after preprocess).

A form name Unicode::Normalize::normalize() accepts will be applied as $normalization_form. Acceptable names include 'NFD', 'NFC', 'NFKD', and 'NFKC'. See Unicode::Normalize::normalize() for detail. If omitted, 'NFD' is used.

normalization is performed after preprocess (if defined).

Furthermore, special values, undef and "prenormalized", can be used, though they are not concerned with Unicode::Normalize::normalize().

If undef (not a string "undef") is passed explicitly as the value for this key, any normalization is not carried out (this may make tailoring easier if any normalization is not desired). Under (normalization => undef), only contiguous contractions are resolved; e.g. even if A-ring (and A-ring-cedilla) is ordered after Z, A-cedilla-ring would be primary equal to A. In this point, (normalization => undef, preprocess => sub { NFD(shift) }) is not equivalent to (normalization => 'NFD').

In the case of (normalization => "prenormalized"), any normalization is not performed, but discontiguous contractions with combining characters are performed. Therefore (normalization => 'prenormalized', preprocess => sub { NFD(shift) }) is equivalent to (normalization => 'NFD'). If source strings are finely prenormalized, (normalization => 'prenormalized') may save time for normalization.

Except (normalization => undef), Unicode::Normalize is required (see also CAVEAT).

overrideCJK

-- see 7.1 Derived Collation Elements, UTS #10.

By default, CJK unified ideographs are ordered in Unicode codepoint order, but those in the CJK Unified Ideographs block are less than those in the CJK Unified Ideographs Extension A etc.

In the CJK Unified Ideographs block:
U+4E00..U+9FA5 if UCA_Version is 8, 9 or 11.
U+4E00..U+9FBB if UCA_Version is 14 or 16.
U+4E00..U+9FC3 if UCA_Version is 18.
U+4E00..U+9FCB if UCA_Version is 20 or 22.
U+4E00..U+9FCC if UCA_Version is 24 to 30.
U+4E00..U+9FD5 if UCA_Version is 32 or 34.
U+4E00..U+9FEA if UCA_Version is 36.
U+4E00..U+9FEF if UCA_Version is 38, 40 or 41.
U+4E00..U+9FFC if UCA_Version is 43.

In the CJK Unified Ideographs Extension blocks:
Ext.A (U+3400..U+4DB5)   if UCA_Version is  8 to 41.
Ext.A (U+3400..U+4DBF)   if UCA_Version is 43.
Ext.B (U+20000..U+2A6D6) if UCA_Version is  8 to 41.
Ext.B (U+20000..U+2A6DD) if UCA_Version is 43.
Ext.C (U+2A700..U+2B734) if UCA_Version is 20 or later.
Ext.D (U+2B740..U+2B81D) if UCA_Version is 22 or later.
Ext.E (U+2B820..U+2CEA1) if UCA_Version is 32 or later.
Ext.F (U+2CEB0..U+2EBE0) if UCA_Version is 36 or later.
Ext.G (U+30000..U+3134A) if UCA_Version is 43.

Through overrideCJK, ordering of CJK unified ideographs (including extensions) can be overridden.

ex. CJK unified ideographs in the JIS code point order.

overrideCJK => sub {
    my $u = shift;             # get a Unicode codepoint
    my $b = pack('n', $u);     # to UTF-16BE
    my $s = your_unicode_to_sjis_converter($b); # convert
    my $n = unpack('n', $s);   # convert sjis to short
    [ $n, 0x20, 0x2, $u ];     # return the collation element
},

The return value may be an arrayref of 1st to 4th weights as shown above. The return value may be an integer as the primary weight as shown below. If undef is returned, the default derived collation element will be used.

overrideCJK => sub {
    my $u = shift;             # get a Unicode codepoint
    my $b = pack('n', $u);     # to UTF-16BE
    my $s = your_unicode_to_sjis_converter($b); # convert
    my $n = unpack('n', $s);   # convert sjis to short
    return $n;                 # return the primary weight
},

The return value may be a list containing zero or more of an arrayref, an integer, or undef.

ex. ignores all CJK unified ideographs.

overrideCJK => sub {()}, # CODEREF returning empty list

 # where ->eq("Pe\x{4E00}rl", "Perl") is true
 # as U+4E00 is a CJK unified ideograph and to be ignorable.

If a false value (including undef) is passed, overrideCJK has no effect. $Collator->change(overrideCJK => 0) resets the old one.

But assignment of weight for CJK unified ideographs in table or entry is still valid. If undef is passed explicitly as the value for this key, weights for CJK unified ideographs are treated as undefined. However when UCA_Version > 8, (overrideCJK => undef) has no special meaning.

Note: In addition to them, 12 CJK compatibility ideographs (U+FA0E, U+FA0F, U+FA11, U+FA13, U+FA14, U+FA1F, U+FA21, U+FA23, U+FA24, U+FA27, U+FA28, U+FA29) are also treated as CJK unified ideographs. But they can't be overridden via overrideCJK when you use DUCET, as the table includes weights for them. table or entry has priority over overrideCJK.

overrideHangul

-- see 7.1 Derived Collation Elements, UTS #10.

By default, Hangul syllables are decomposed into Hangul Jamo, even if (normalization => undef). But the mapping of Hangul syllables may be overridden.

This parameter works like overrideCJK, so see there for examples.

If you want to override the mapping of Hangul syllables, NFD and NFKD are not appropriate, since NFD and NFKD will decompose Hangul syllables before overriding. FCD may decompose Hangul syllables as the case may be.

If a false value (but not undef) is passed, overrideHangul has no effect. $Collator->change(overrideHangul => 0) resets the old one.

If undef is passed explicitly as the value for this key, weight for Hangul syllables is treated as undefined without decomposition into Hangul Jamo. But definition of weight for Hangul syllables in table or entry is still valid.

overrideOut

-- see 7.1.1 Handling Ill-Formed Code Unit Sequences, UTS #10.

Perl seems to allow out-of-range values (greater than 0x10FFFF). By default, out-of-range values are replaced with U+FFFD (REPLACEMENT CHARACTER) when UCA_Version >= 22, or ignored when UCA_Version <= 20.

When UCA_Version >= 22, the weights of out-of-range values can be overridden. Though table or entry are available for them, out-of-range values are too many.

overrideOut can perform it algorithmically. This parameter works like overrideCJK, so see there for examples.

ex. ignores all out-of-range values.

overrideOut => sub {()}, # CODEREF returning empty list

If a false value (including undef) is passed, overrideOut has no effect. $Collator->change(overrideOut => 0) resets the old one.

NOTE ABOUT U+FFFD:

UCA recommends that out-of-range values should not be ignored for security reasons. Say, "pe\x{110000}rl" should not be equal to "perl". However, U+FFFD is wrongly mapped to a variable collation element in DUCET for Unicode 6.0.0 to 6.2.0, that means out-of-range values will be ignored when variable isn't Non-ignorable.

The mapping of U+FFFD is corrected in Unicode 6.3.0. see http://www.unicode.org/reports/tr10/tr10-28.html#Trailing_Weights (7.1.4 Trailing Weights). Such a correction is reproduced by this.

overrideOut => sub { 0xFFFD }, # CODEREF returning a very large integer

This workaround is unnecessary since Unicode 6.3.0.

preprocess

-- see 5.4 Preprocessing, UTS #10.

If specified, the coderef is used to preprocess each string before the formation of sort keys.

ex. dropping English articles, such as "a" or "the". Then, "the pen" is before "a pencil".

preprocess => sub {
      my $str = shift;
      $str =~ s/\b(?:an?|the)\s+//gi;
      return $str;
   },

preprocess is performed before normalization (if defined).

ex. decoding strings in a legacy encoding such as shift-jis:

$sjis_collator = Unicode::Collate->new(
    preprocess => \&your_shiftjis_to_unicode_decoder,
);
@result = $sjis_collator->sort(@shiftjis_strings);

Note: Strings returned from the coderef will be interpreted according to Perl's Unicode support. See perlunicode, perluniintro, perlunitut, perlunifaq, utf8.