man Unicode::Collate () - Unicode Collation Algorithm

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.

  # If %tailoring is false (i.e. empty),
  # $Collator should do the default collation.

DESCRIPTION

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

Constructor and Tailoring

The CWnew method returns a collator object.

   $Collator = Unicode::Collate->new(
      UCA_Version => $UCA_Version,
      alternate => $alternate, # deprecated: use of 'variable' is recommended.
      backwards => $levelNumber, # or \@levelNumbers
      entry => $element,
      hangul_terminator => $term_primary_weight,
      ignoreName => qr/$ignoreName/,
      ignoreChar => qr/$ignoreChar/,
      katakana_before_hiragana => $bool,
      level => $collationLevel,
      normalization  => $normalization_form,
      overrideCJK => \&overrideCJK,
      overrideHangul => \&overrideHangul,
      preprocess => \&preprocess,
      rearrange => \@charList,
      table => $filename,
      undefName => qr/$undefName/,
      undefChar => qr/$undefChar/,
      upper_before_lower => $bool,
      variable => $variable,
   );
UCA_Version
If the tracking version number of the older UCA is given, the older behavior of that tracking version is emulated on collating. If omitted, the return value of CWUCA_Version() is used. The supported tracking version: 8, 9, or 11. This parameter may be removed in the future version, as switching the algorithm would affect the performance.
backwards
-- see 3.1.2 French Accents, UTS #10.
     backwards => $levelNumber or \@levelNumbers
Weights in reverse order; ex. level 2 (diacritic ordering) in French. If omitted, forwards at all the levels.
entry
-- see 3.1 Linguistic Features; 3.2.1 File Format, UTS #10. If the same character (or a sequence of characters) exists in the collation element table through CWtable, mapping to collation elements is overrided. 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 CW';') must be a Unicode code point (defined as hexadecimal), but not a native code point. So CW0063 must always denote CWU+0063, but not a character of CW"\x63". Weighting may vary depending on collation element table. So ensure the weights defined in CWentry will be consistent with those in the collation element table loaded via CWtable. In DUCET v4.0.0, primary weight of CWC is CW0E60 and that of CWD is CW0E6D. So setting primary weight of CWCH to CW0E6A (as a value between CW0E60 and CW0E6D) makes ordering as CWC < CH < D. Exactly speaking DUCET already has some characters between CWC and CWD: CWsmall capital C (CWU+1D04) with primary weight CW0E64, CWc-hook/C-hook (CWU+0188/U+0187) with CW0E65, and CWc-curl (CWU+0255) with CW0E69. Then primary weight CW0E6A for CWCH makes CWCH ordered between CWc-curl and CWD.
hangul_terminator
-- see Condition B.2. in 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 CWhangul_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.
ignoreName
ignoreChar
-- see Completely Ignorable, 3.2.2 Variable Weighting, UTS #10. Makes the entry in the table completely ignorable; i.e. as if the weights were zero at all level. E.g. when 'a' and 'e' are ignorable, 'element' is equal to 'lament' (or 'lmnt').
level
-- see 4.3 Form a sort key for each string, 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.
normalization
-- see 4.1 Normalize each input string, UTS #10. If specified, strings are normalized before preparation of sort keys (the normalization is executed after preprocess). A form name CWUnicode::Normalize::normalize() accepts will be applied as CW$normalization_form. Acceptable names include CW'NFD', CW'NFC', CW'NFKD', and CW'NFKC'. See CWUnicode::Normalize::normalize() for detail. If omitted, CW'NFD' is used. CWnormalization is performed after CWpreprocess (if defined). Furthermore, special values, CWundef and CW"prenormalized", can be used, though they are not concerned with CWUnicode::Normalize::normalize(). If CWundef (not a string CW"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 CW(normalization => undef), only contiguous contractions are resolved; e.g. even if CWA-ring (and CWA-ring-cedilla) is ordered after CWZ, CWA-cedilla-ring would be primary equal to CWA. In this point, CW(normalization => undef, preprocess => sub { NFD(shift) }) is not equivalent to CW(normalization => 'NFD'). In the case of CW(normalization => "prenormalized"), any normalization is not performed, but non-contiguous contractions with combining characters are performed. Therefore CW(normalization => 'prenormalized', preprocess => sub { NFD(shift) }) is equivalent to CW(normalization => 'NFD'). If source strings are finely prenormalized, CW(normalization => 'prenormalized') may save time for normalization. Except CW(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 CWCJK Unified Ideographs [CWU+4E00 to CWU+9FA5] are lesser than CWCJK Unified Ideographs Extension [CWU+3400 to CWU+4DB5 and CWU+20000 to CWU+2A6D6]. Through CWoverrideCJK, ordering of CJK Unified Ideographs can be overrided. 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
  },
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 CWundef is passed explicitly as the value for this key, weights for CJK Unified Ideographs are treated as undefined. But assignment of weight for CJK Unified Ideographs in table or CWentry is still valid.
overrideHangul
-- see 7.1 Derived Collation Elements, UTS #10. By default, Hangul Syllables are decomposed into Hangul Jamo, even if CW(normalization => undef). But the mapping of Hangul Syllables may be overrided. This tag works like CWoverrideCJK, so see there for examples. If you want to override the mapping of Hangul Syllables, NFD, NFKD, and FCD are not appropriate, since they will decompose Hangul Syllables before overriding. If CWundef 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 CWentry is still valid.
preprocess
-- see 5.1 Preprocessing, UTS #10. If specified, the coderef is used to preprocess 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;
        },
CWpreprocess is performed before CWnormalization (if defined).
rearrange
-- see 3.1.3 Rearrangement, UTS #10. Characters that are not coded in logical order and to be rearranged. By default,
    rearrange => [ 0x0E40..0x0E44, 0x0EC0..0x0EC4 ],
If you want to disallow any rearrangement, pass CWundef or CW[] (a reference to an empty list) as the value for this key. According to the version 9 of UCA, this parameter shall not be used; but it is not warned at present.
table
-- see 3.2 Default Unicode Collation Element Table, UTS #10. You can use another collation element table if desired. The table file should locate in the Unicode/Collate directory on CW@INC. Say, if the filename is Foo.txt the table file is searched as Unicode/Collate/Foo.txt in <@INC>. By default, allkeys.txt (as the filename of DUCET) is used. If CWundef is passed explicitly as the value for this key, no file is read (but you can define collation elements via CWentry). A typical way to define a collation element table without any file of table:
   $onlyABC = Unicode::Collate->new(
       table => undef,
       entry => << 'ENTRIES',
0061 ; [.0101.0020.0002.0061] # LATIN SMALL LETTER A
0041 ; [.0101.0020.0008.0041] # LATIN CAPITAL LETTER A
0062 ; [.0102.0020.0002.0062] # LATIN SMALL LETTER B
0042 ; [.0102.0020.0008.0042] # LATIN CAPITAL LETTER B
0063 ; [.0103.0020.0002.0063] # LATIN SMALL LETTER C
0043 ; [.0103.0020.0008.0043] # LATIN CAPITAL LETTER C
ENTRIES
    );
undefName
undefChar
-- see 6.3.4 Reducing the Repertoire, UTS #10. Undefines the collation element as if it were unassigned in the table. This reduces the size of the table. If an unassigned character appears in the string to be collated, the sort key is made from its codepoint as a single-character collation element, as it is greater than any other assigned collation elements (in the codepoint order among the unassigned characters). But, it'd be better to ignore characters unfamiliar to you and maybe never used. ex. Collation weights for beyond-BMP characters are not stored in object:
    undefChar => qr/[^\0-\x{fffd}]/,
katakana_before_hiragana
upper_before_lower
-- see 6.6 Case Comparisons; 7.3.1 Tertiary Weight Table, UTS #10. By default, lowercase is before uppercase and hiragana is before katakana. If the tag is made true, this is reversed. NOTE: These tags simplemindedly assume any lowercase/uppercase or 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, these tags don't work validly.
variable
alternate
-- see 3.2.2 Variable Weighting, UTS #10. (the title in UCA version 8: Alternate Weighting) This key allows to variable weighting for variable collation elements, which are marked with an ASTERISK in the table (NOTE: Many punction marks and symbols are variable in allkeys.txt).
   variable => 'blanked', 'non-ignorable', 'shifted', or 'shift-trimmed'.
These names are case-insensitive. By default (if specification is omitted), 'shifted' is adopted.
   'Blanked'        Variable elements are made ignorable at levels 1 through 3;
                    considered at the 4th level.
   'Non-Ignorable'  Variable elements are not reset to ignorable.
   'Shifted'        Variable elements are made ignorable at levels 1 through 3
                    their level 4 weight is replaced by the old level 1 weight.
                    Level 4 weight for Non-Variable elements is 0xFFFF.
   'Shift-Trimmed'  Same as 'shifted', but all FFFF's at the 4th level
                    are trimmed.
For backward compatibility, CWalternate can be used as an alias for CWvariable.

Methods for Collation

Sorts a list of strings. Returns 1 (when CW$a is greater than CW$b) or 0 (when CW$a is equal to CW$b) or -1 (when CW$a is lesser than CW$b). They works like the same name operators as theirs.

   eq : whether $a is equal to $b.
   ne : whether $a is not equal to $b.
   lt : whether $a is lesser than $b.
   le : whether $a is lesser than $b or equal to $b.
   gt : whether $a is greater than $b.
   ge : whether $a is greater than $b or equal to $b.
-- see 4.3 Form a sort key for each string, UTS #10. Returns a sort key. You compare the sort keys using a binary comparison and get the result of the comparison of the strings using UCA.
   $Collator->getSortKey($a) cmp $Collator->getSortKey($b)
      is equivalent to
   $Collator->cmp($a, $b)
   use Unicode::Collate;
   my $c = Unicode::Collate->new();
   print $c->viewSortKey("Perl"),"\n";
   # output:
   # [0B67 0A65 0B7F 0B03 | 0020 0020 0020 0020 | 0008 0002 0002 0002 | FFFF FFFF FFFF FFFF]
   #  Level 1               Level 2               Level 3               Level 4
    (If C<UCA_Version> is 8, the output is slightly different.)

Methods for Searching

DISCLAIMER: If CWpreprocess or CWnormalization tag is true for CW$Collator, calling these methods (CWindex, CWmatch, CWgmatch, CWsubst, CWgsubst) is croaked, as the position and the length might differ from those on the specified string. (And CWrearrange and CWhangul_terminator tags are neglected.)

The CWmatch, CWgmatch, CWsubst, CWgsubst methods work like CWm//, CWm//g, CWs///, CWs///g, respectively, but they are not aware of any pattern, but only a literal substring. If CW$substring matches a part of CW$string, returns the position of the first occurrence of the matching part in scalar context; in list context, returns a two-element list of the position and the length of the matching part. If CW$substring does not match any part of CW$string, returns CW-1 in scalar context and an empty list in list context. e.g. you say

  my $Collator = Unicode::Collate->new( normalization => undef, level => 1 );
                                     # (normalization => undef) is REQUIRED.
  my $str = "Ich muß studieren Perl.";
  my $sub = "MÜSS";
  my $match;
  if (my($pos,$len) = $Collator->index($str, $sub)) {
      $match = substr($str, $pos, $len);
  }
and get CW"muß" in CW$match since CW"muß" is primary equal to CW"MÜSS". If CW$substring matches a part of CW$string, in scalar context, returns a reference to the first occurrence of the matching part (CW$match_ref is always true if matches, since every reference is true); in list context, returns the first occurrence of the matching part. If CW$substring does not match any part of CW$string, returns CWundef in scalar context and an empty list in list context. e.g.
    if ($match_ref = $Collator->match($str, $sub)) { # scalar context
        print "matches [$$match_ref].\n";
    } else {
        print "doesn't match.\n";
    }
     or
    if (($match) = $Collator->match($str, $sub)) { # list context
        print "matches [$match].\n";
    } else {
        print "doesn't match.\n";
    }
If CW$substring matches a part of CW$string, returns all the matching parts (or matching count in scalar context). If CW$substring does not match any part of CW$string, returns an empty list. If CW$substring matches a part of CW$string, the first occurrence of the matching part is replaced by CW$replacement (CW$string is modified) and return CW$count (always equals to CW1). CW$replacement can be a CWCODEREF, taking the matching part as an argument, and returning a string to replace the matching part (a bit similar to CWs/(..)/$coderef->($1)/e). If CW$substring matches a part of CW$string, all the occurrences of the matching part is replaced by CW$replacement (CW$string is modified) and return CW$count. CW$replacement can be a CWCODEREF, taking the matching part as an argument, and returning a string to replace the matching part (a bit similar to CWs/(..)/$coderef->($1)/eg). e.g.
  my $Collator = Unicode::Collate->new( normalization => undef, level => 1 );
                                     # (normalization => undef) is REQUIRED.
  my $str = "Camel ass came\x{301}l CAMEL horse cAm\0E\0L...";
  $Collator->gsubst($str, "camel", sub { "<b>$_[0]</b>" });
  # now $str is "<b>Camel</b> ass <b>came\x{301}l</b> <b>CAMEL</b> horse <b>cAm\0E\0L</b>...";
  # i.e., all the camels are made bold-faced.

Other Methods

Change the value of specified keys and returns the changed part.

    $Collator = Unicode::Collate->new(level => 4);
    $Collator->eq("perl", "PERL"); # false
    %old = $Collator->change(level => 2); # returns (level => 4).
    $Collator->eq("perl", "PERL"); # true
    $Collator->change(%old); # returns (level => 2).
    $Collator->eq("perl", "PERL"); # false
Not all CW(key,value)s are allowed to be changed. See also CW@Unicode::Collate::ChangeOK and CW@Unicode::Collate::ChangeNG. In the scalar context, returns the modified collator (but it is not a clone from the original).
    $Collator->change(level => 2)->eq("perl", "PERL"); # true
    $Collator->eq("perl", "PERL"); # true; now max level is 2nd.
    $Collator->change(level => 4)->eq("perl", "PERL"); # false
Returns the version number (a string) of the Unicode Standard which the CWtable file used by the collator object is based on. If the table does not include a version line (starting with CW@version), returns CW"unknown". Returns the tracking version number of UTS #10 this module consults. Returns the version number of UTS #10 this module consults.

EXPORT

None by default.

CAVEAT

Use of the CWnormalization parameter requires the Unicode::Normalize module.

If you need not it (say, in the case when you need not handle any combining characters), assign CWnormalization => undef explicitly.

-- see 6.5 Avoiding Normalization, UTS #10.

Conformance Test

The Conformance Test for the UCA is available under <http://www.unicode.org/Public/UCA/>.

For CollationTest_SHIFTED.txt, a collator via CWUnicode::Collate->new( ) should be used; for CollationTest_NON_IGNORABLE.txt, a collator via CWUnicode::Collate->new(variable => "non-ignorable", level => 3).

Unicode::Normalize is required to try The Conformance Test.

AUTHOR

SADAHIRO Tomoyuki <SADAHIRO@cpan.org>

  http://homepage1.nifty.com/nomenclator/perl/

  Copyright(C) 2001-2004, SADAHIRO Tomoyuki. Japan. All rights reserved.

  This library is free software; you can redistribute it
  and/or modify it under the same terms as Perl itself.

SEE ALSO

Unicode Collation Algorithm - UTS #10
<http://www.unicode.org/reports/tr10/>
The Default Unicode Collation Element Table (DUCET)
<http://www.unicode.org/Public/UCA/latest/allkeys.txt>
The conformance test for the UCA
<http://www.unicode.org/Public/UCA/latest/CollationTest.html> <http://www.unicode.org/Public/UCA/latest/CollationTest.zip>
Hangul Syllable Type
<http://www.unicode.org/Public/UNIDATA/HangulSyllableType.txt>
Unicode Normalization Forms - UAX #15
<http://www.unicode.org/reports/tr15/>
Unicode::Normalize