1 package Unicode::Collate;
4 unless ("A" eq pack('U', 0x41)) {
5 die "Unicode::Collate cannot stringify a Unicode code point\n";
17 our $VERSION = '0.26';
18 our $PACKAGE = __PACKAGE__;
20 our @ISA = qw(Exporter);
22 our %EXPORT_TAGS = ();
26 (our $Path = $INC{'Unicode/Collate.pm'}) =~ s/\.pm$//;
27 our $KeyFile = "allkeys.txt";
31 eval { require Unicode::UCD };
34 $UNICODE_VERSION = Unicode::UCD::UnicodeVersion();
38 foreach my $d (@INC) {
39 $f = File::Spec->catfile($d, "unicode", "Unicode.301");
41 $UNICODE_VERSION = '3.0.1';
49 use constant TRUE => 1;
50 use constant FALSE => "";
51 use constant NOMATCHPOS => -1;
53 # A coderef to get combining class imported from Unicode::Normalize
54 # (i.e. \&Unicode::Normalize::getCombinClass).
55 # This is also used as a HAS_UNICODE_NORMALIZE flag.
59 use constant MinLevel => 1;
60 use constant MaxLevel => 4;
62 # Minimum weights at level 2 and 3, respectively
63 use constant Min2Wt => 0x20;
64 use constant Min3Wt => 0x02;
66 # Shifted weight at 4th level
67 use constant Shift4Wt => 0xFFFF;
69 # Variable weight at 1st level.
70 # This is a negative value but should be regarded as zero on collation.
71 # This is for distinction of variable chars from level 3 ignorable chars.
72 use constant Var1Wt => -1;
75 # A boolean for Variable and 16-bit weights at 4 levels of Collation Element
76 # PROBLEM: The Default Unicode Collation Element Table
77 # has weights over 0xFFFF at the 4th level.
78 # The tie-breaking in the variable weights
79 # other than "shift" (as well as "shift-trimmed") is unreliable.
80 use constant VCE_TEMPLATE => 'Cn4';
82 # A sort key: 16-bit weights
83 # See also the PROBLEM on VCE_TEMPLATE above.
84 use constant KEY_TEMPLATE => 'n*';
86 # Level separator in a sort key:
87 # i.e. pack(KEY_TEMPLATE, 0)
88 use constant LEVEL_SEP => "\0\0";
90 # As Unicode code point separator for hash keys.
91 # A joined code point string (denoted by JCPS below)
92 # like "65;768" is used for internal processing
93 # instead of Perl's Unicode string like "\x41\x{300}",
94 # as the native code point is different from the Unicode code point
96 # This character must not be included in any stringified
97 # representation of an integer.
98 use constant CODE_SEP => ';';
100 # boolean values of variable weights
101 use constant NON_VAR => 0; # Non-Variable character
102 use constant VAR => 1; # Variable character
104 # Logical_Order_Exception in PropList.txt
105 # TODO: synchronization with change of PropList.txt.
106 our $DefaultRearrange = [ 0x0E40..0x0E44, 0x0EC0..0x0EC4 ];
108 sub UCA_Version { "9" }
110 sub Base_Unicode_Version { $UNICODE_VERSION || 'unknown' }
115 return pack('U*', @_);
119 return unpack('U*', pack('U*').shift);
126 blanked non-ignorable shifted shift-trimmed
130 alternate backwards level normalization rearrange
131 katakana_before_hiragana upper_before_lower
132 overrideHangul overrideCJK preprocess UCA_Version
136 entry entries table maxlength
137 ignoreChar ignoreName undefChar undefName
138 versionTable alternateTable backwardsTable forwardsTable rearrangeTable
139 derivCode normCode rearrangeHash L3_ignorable
142 # The hash key 'ignored' is deleted at v 0.21.
143 # The hash key 'isShift' is deleted at v 0.23.
144 # The hash key 'combining' is deleted at v 0.24.
146 my (%ChangeOK, %ChangeNG);
147 @ChangeOK{ @ChangeOK } = ();
148 @ChangeNG{ @ChangeNG } = ();
154 foreach my $k (keys %hash) {
155 if (exists $ChangeOK{$k}) {
156 $old{$k} = $self->{$k};
157 $self->{$k} = $hash{$k};
159 elsif (exists $ChangeNG{$k}) {
160 croak "change of $k via change() is not allowed!";
164 $self->checkCollator;
165 return wantarray ? %old : $self;
171 croak sprintf "Illegal level %d (in \$self->{%s}) lower than %d.",
172 $level, $key, MinLevel if MinLevel > $level;
173 croak sprintf "Unsupported level %d (in \$self->{%s}) higher than %d ",
174 $level, $key, MaxLevel if MaxLevel < $level;
179 _checkLevel($self->{level}, "level");
182 $self->{UCA_Version} == 8 ? \&_derivCE_8 :
183 $self->{UCA_Version} == 9 ? \&_derivCE_9 :
184 croak "Illegal UCA version (passed $self->{UCA_Version}).";
186 $self->{alternate} = lc($self->{alternate});
187 croak "$PACKAGE unknown alternate tag name: $self->{alternate}"
188 unless exists $AlternateOK{ $self->{alternate} };
190 if (! defined $self->{backwards}) {
191 $self->{backwardsFlag} = 0;
193 elsif (! ref $self->{backwards}) {
194 _checkLevel($self->{backwards}, "backwards");
195 $self->{backwardsFlag} = 1 << $self->{backwards};
199 $self->{backwardsFlag} = 0;
200 for my $b (@{ $self->{backwards} }) {
201 _checkLevel($b, "backwards");
204 for my $v (sort keys %level) {
205 $self->{backwardsFlag} += 1 << $v;
209 $self->{rearrange} = []
210 if ! defined $self->{rearrange};
211 croak "$PACKAGE: A list for rearrangement must be store in an ARRAYREF"
212 if ! ref $self->{rearrange};
214 # keys of $self->{rearrangeHash} are $self->{rearrange}.
215 $self->{rearrangeHash} = undef;
217 if (@{ $self->{rearrange} }) {
218 @{ $self->{rearrangeHash} }{ @{ $self->{rearrange} } } = ();
221 $self->{normCode} = undef;
223 if (defined $self->{normalization}) {
224 eval { require Unicode::Normalize };
225 croak "Unicode/Normalize.pm is required to normalize strings: $@"
228 Unicode::Normalize->import();
229 $getCombinClass = \&Unicode::Normalize::getCombinClass
230 if ! $getCombinClass;
233 $self->{normalization} =~ /^(?:NF)?C$/ ? \&NFC :
234 $self->{normalization} =~ /^(?:NF)?D$/ ? \&NFD :
235 $self->{normalization} =~ /^(?:NF)?KC$/ ? \&NFKC :
236 $self->{normalization} =~ /^(?:NF)?KD$/ ? \&NFKD :
237 croak "$PACKAGE unknown normalization form name: "
238 . $self->{normalization};
246 my $self = bless { @_ }, $class;
248 # If undef is passed explicitly, no file is read.
249 $self->{table} = $KeyFile if ! exists $self->{table};
250 $self->read_table if defined $self->{table};
252 if ($self->{entry}) {
253 $self->parseEntry($_) foreach split /\n/, $self->{entry};
256 $self->{level} ||= MaxLevel;
257 $self->{UCA_Version} ||= UCA_Version();
259 $self->{overrideHangul} = ''
260 if ! exists $self->{overrideHangul};
261 $self->{overrideCJK} = ''
262 if ! exists $self->{overrideCJK};
263 $self->{normalization} = 'D'
264 if ! exists $self->{normalization};
265 $self->{alternate} = $self->{alternateTable} || 'shifted'
266 if ! exists $self->{alternate};
267 $self->{rearrange} = $self->{rearrangeTable} || $DefaultRearrange
268 if ! exists $self->{rearrange};
269 $self->{backwards} = $self->{backwardsTable}
270 if ! exists $self->{backwards};
272 $self->checkCollator;
279 my $file = $self->{table} ne '' ? $self->{table} : $KeyFile;
281 my $filepath = File::Spec->catfile($Path, $file);
282 open my $fk, "<$filepath"
283 or croak "File does not exist at $filepath";
288 if (/^\s*\@version\s*(\S*)/) {
289 $self->{versionTable} ||= $1;
291 elsif (/^\s*\@alternate\s+(\S*)/) {
292 $self->{alternateTable} ||= $1;
294 elsif (/^\s*\@backwards\s+(\S*)/) {
295 push @{ $self->{backwardsTable} }, $1;
297 elsif (/^\s*\@forwards\s+(\S*)/) { # parhaps no use
298 push @{ $self->{forwardsTable} }, $1;
300 elsif (/^\s*\@rearrange\s+(.*)/) { # (\S*) is NG
301 push @{ $self->{rearrangeTable} }, _getHexArray($1);
305 $self->parseEntry($_);
312 ## get $line, parse it, and write an entry in $self
318 my($name, $entry, @uv, @key);
320 return if $line !~ /^\s*[0-9A-Fa-f]/;
322 # removes comment and gets name
324 if $line =~ s/[#%]\s*(.*)//;
325 return if defined $self->{undefName} && $name =~ /$self->{undefName}/;
328 my($e, $k) = split /;/, $line;
329 croak "Wrong Entry: <charList> must be separated by ';' from <collElement>"
332 @uv = _getHexArray($e);
335 $entry = join(CODE_SEP, @uv); # in JCPS
337 if (defined $self->{undefChar} || defined $self->{ignoreChar}) {
338 my $ele = pack_U(@uv);
340 # regarded as if it were not entried in the table
342 if defined $self->{undefChar} && $ele =~ /$self->{undefChar}/;
344 # replaced as completely ignorable
345 $k = '[.0000.0000.0000.0000]'
346 if defined $self->{ignoreChar} && $ele =~ /$self->{ignoreChar}/;
349 # replaced as completely ignorable
350 $k = '[.0000.0000.0000.0000]'
351 if defined $self->{ignoreName} && $name =~ /$self->{ignoreName}/;
353 my $is_L3_ignorable = TRUE;
355 foreach my $arr ($k =~ /\[([^\[\]]+)\]/g) { # SPACEs allowed
356 my $var = $arr =~ /\*/; # exactly /^\*/ but be lenient.
357 my @wt = _getHexArray($arr);
358 push @key, pack(VCE_TEMPLATE, $var, @wt);
359 $is_L3_ignorable = FALSE
360 if $wt[0] + $wt[1] + $wt[2] != 0;
361 # if $arr !~ /[1-9A-Fa-f]/; NG
362 # Conformance Test shows L3-ignorable is completely ignorable.
363 # For expansion, an entry $is_L3_ignorable
364 # if and only if "all" CEs are [.0000.0000.0000].
367 $self->{entries}{$entry} = \@key;
369 $self->{L3_ignorable}{$uv[0]} = TRUE
370 if @uv == 1 && $is_L3_ignorable;
372 # Contraction is to be considered in the range of this maxlength.
373 $self->{maxlength}{$uv[0]} = scalar @uv
379 ## arrayref[weights] = altCE(VCE)
384 my($var, @wt) = unpack(VCE_TEMPLATE, shift);
386 $self->{alternate} eq 'blanked' ?
387 $var ? [Var1Wt, 0, 0, $wt[3]] : \@wt :
388 $self->{alternate} eq 'non-ignorable' ?
390 $self->{alternate} eq 'shifted' ?
391 $var ? [Var1Wt, 0, 0, $wt[0] ]
392 : [ @wt[0..2], $wt[0]+$wt[1]+$wt[2] ? Shift4Wt : 0 ] :
393 $self->{alternate} eq 'shift-trimmed' ?
394 $var ? [Var1Wt, 0, 0, $wt[0] ] : [ @wt[0..2], 0 ] :
395 croak "$PACKAGE unknown alternate name: $self->{alternate}";
401 $self->visualizeSortKey($self->getSortKey(@_));
407 my $view = join " ", map sprintf("%04X", $_), unpack(KEY_TEMPLATE, shift);
409 if ($self->{UCA_Version} <= 8) {
410 $view =~ s/ ?0000 ?/|/g;
412 $view =~ s/\b0000\b/|/g;
419 ## arrayref of JCPS = splitCE(string to be collated)
420 ## arrayref of arrayref[JCPS, ini_pos, fin_pos] = splitCE(string, true)
427 my $code = $self->{preprocess};
428 my $norm = $self->{normCode};
429 my $ent = $self->{entries};
430 my $max = $self->{maxlength};
431 my $reH = $self->{rearrangeHash};
432 my $ign = $self->{L3_ignorable};
433 my $ver9 = $self->{UCA_Version} > 8;
438 $code and croak "Preprocess breaks character positions. "
439 . "Don't use with index(), match(), etc.";
440 $norm and croak "Normalization breaks character positions. "
441 . "Don't use with index(), match(), etc.";
446 $str = &$code($str) if ref $code;
447 $str = &$norm($str) if ref $norm;
450 # get array of Unicode code point of string.
451 my @src = unpack_U($str);
454 # Character positions are not kept if rearranged,
455 # then neglected if $wLen is true.
456 if ($reH && ! $wLen) {
457 for (my $i = 0; $i < @src; $i++) {
458 if (exists $reH->{ $src[$i] } && $i + 1 < @src) {
459 ($src[$i], $src[$i+1]) = ($src[$i+1], $src[$i]);
466 # To remove a character marked as a completely ignorable.
467 for (my $i = 0; $i < @src; $i++) {
468 $src[$i] = undef if $ign->{ $src[$i] };
472 for (my $i = 0; $i < @src; $i++) {
473 next if _isNonCharacter($src[$i]);
478 if ($max->{$ce}) { # contract
481 for (my $p = $i + 1; $p < @src; $p++) {
482 next if ! defined $src[$p];
483 $temp_ce .= CODE_SEP . $src[$p];
484 if ($ent->{$temp_ce}) {
491 # with Combining Char (UTS#10, 4.2.1).
492 # requires Unicode::Normalize.
493 # Not be $wLen, as not croaked due to $norm.
494 if ($getCombinClass) {
495 for (my $p = $i + 1; $p < @src; $p++) {
496 next if ! defined $src[$p];
497 last unless $getCombinClass->($src[$p]);
498 my $tail = CODE_SEP . $src[$p];
499 if ($ent->{$ce.$tail}) {
507 for (my $p = $i + 1; $p < @src; $p++) {
508 last if defined $src[$p];
513 push @buf, $wLen ? [$ce, $i_orig, $i + 1] : $ce;
520 ## list of arrayrefs of weights = getWt(JCPS)
526 my $ent = $self->{entries};
527 my $cjk = $self->{overrideCJK};
528 my $hang = $self->{overrideHangul};
529 my $der = $self->{derivCode};
531 return if !defined $ce;
532 return map($self->altCE($_), @{ $ent->{$ce} })
535 # CE must not be a contraction, then it's a code point.
538 if (0xAC00 <= $u && $u <= 0xD7A3) { # is Hangul Syllale
539 return map $self->altCE($_),
541 ? map(pack(VCE_TEMPLATE, NON_VAR, @$_), &$hang($u))
544 $ent->{$_} ? @{ $ent->{$_} } : $der->($_);
548 elsif (0x3400 <= $u && $u <= 0x4DB5 ||
549 0x4E00 <= $u && $u <= 0x9FA5 ||
550 0x20000 <= $u && $u <= 0x2A6D6) { # CJK Ideograph
551 return map $self->altCE($_),
553 ? map(pack(VCE_TEMPLATE, NON_VAR, @$_), &$cjk($u))
554 : defined $cjk && $self->{UCA_Version} <= 8 && $u < 0x10000
555 ? pack(VCE_TEMPLATE, NON_VAR, $u, Min2Wt, Min3Wt, $u)
559 return map $self->altCE($_), $der->($u);
565 ## string sortkey = getSortKey(string arg)
570 my $lev = $self->{level};
571 my $rCE = $self->splitCE(shift); # get an arrayref of JCPS
572 my $ver9 = $self->{UCA_Version} > 8;
573 my $v2i = $self->{alternate} ne 'non-ignorable';
576 my (@buf, $last_is_variable);
578 foreach my $wt (map $self->getWt($_), @$rCE) {
580 if ($wt->[0] == 0) { # ignorable
581 next if $last_is_variable;
583 $last_is_variable = ($wt->[0] == Var1Wt);
590 my @ret = ([],[],[],[]);
591 foreach my $v (0..$lev-1) {
592 foreach my $b (@buf) {
593 push @{ $ret[$v] }, $b->[$v]
598 # modification of tertiary weights
599 if ($self->{upper_before_lower}) {
600 foreach (@{ $ret[2] }) {
601 if (0x8 <= $_ && $_ <= 0xC) { $_ -= 6 } # lower
602 elsif (0x2 <= $_ && $_ <= 0x6) { $_ += 6 } # upper
603 elsif ($_ == 0x1C) { $_ += 1 } # square upper
604 elsif ($_ == 0x1D) { $_ -= 1 } # square lower
607 if ($self->{katakana_before_hiragana}) {
608 foreach (@{ $ret[2] }) {
609 if (0x0F <= $_ && $_ <= 0x13) { $_ -= 2 } # katakana
610 elsif (0x0D <= $_ && $_ <= 0x0E) { $_ += 5 } # hiragana
614 if ($self->{backwardsFlag}) {
615 for (my $v = MinLevel; $v <= MaxLevel; $v++) {
616 if ($self->{backwardsFlag} & (1 << $v)) {
617 @{ $ret[$v-1] } = reverse @{ $ret[$v-1] };
622 join LEVEL_SEP, map pack(KEY_TEMPLATE, @$_), @ret;
627 ## int compare = cmp(string a, string b)
629 sub cmp { $_[0]->getSortKey($_[1]) cmp $_[0]->getSortKey($_[2]) }
630 sub eq { $_[0]->getSortKey($_[1]) eq $_[0]->getSortKey($_[2]) }
631 sub ne { $_[0]->getSortKey($_[1]) ne $_[0]->getSortKey($_[2]) }
632 sub lt { $_[0]->getSortKey($_[1]) lt $_[0]->getSortKey($_[2]) }
633 sub le { $_[0]->getSortKey($_[1]) le $_[0]->getSortKey($_[2]) }
634 sub gt { $_[0]->getSortKey($_[1]) gt $_[0]->getSortKey($_[2]) }
635 sub ge { $_[0]->getSortKey($_[1]) ge $_[0]->getSortKey($_[2]) }
638 ## list[strings] sorted = sort(list[strings] arg)
644 sort{ $a->[0] cmp $b->[0] }
645 map [ $obj->getSortKey($_), $_ ], @_;
652 (0x4E00 <= $u && $u <= 0x9FA5)
654 (0x3400 <= $u && $u <= 0x4DB5 || 0x20000 <= $u && $u <= 0x2A6D6)
658 my $aaaa = $base + ($u >> 15);
659 my $bbbb = ($u & 0x7FFF) | 0x8000;
661 pack(VCE_TEMPLATE, NON_VAR, $aaaa, Min2Wt, Min3Wt, $u),
662 pack(VCE_TEMPLATE, NON_VAR, $bbbb, 0, 0, $u);
667 my $aaaa = 0xFF80 + ($code >> 15);
668 my $bbbb = ($code & 0x7FFF) | 0x8000;
670 pack(VCE_TEMPLATE, NON_VAR, $aaaa, 2, 1, $code),
671 pack(VCE_TEMPLATE, NON_VAR, $bbbb, 0, 0, $code);
675 ## "hhhh hhhh hhhh" to (dddd, dddd, dddd)
677 sub _getHexArray { map hex, $_[0] =~ /([0-9a-fA-F]+)/g }
680 # $code *must* be in Hangul syllable.
681 # Check it before you enter here.
685 my $SIndex = $code - 0xAC00;
686 my $LIndex = int( $SIndex / 588);
687 my $VIndex = int(($SIndex % 588) / 28);
688 my $TIndex = $SIndex % 28;
692 $TIndex ? (0x11A7 + $TIndex) : (),
696 sub _isNonCharacter {
698 return ! defined $code # removed
699 || ($code < 0 || 0x10FFFF < $code) # out of range
700 || (($code & 0xFFFE) == 0xFFFE) # ??FFF[EF] (cf. utf8.c)
701 || (0xD800 <= $code && $code <= 0xDFFF) # unpaired surrogates
702 || (0xFDD0 <= $code && $code <= 0xFDEF) # other non-characters
708 ## bool _nonIgnorAtLevel(arrayref weights, int level)
710 sub _nonIgnorAtLevel($$)
713 return if ! defined $wt;
715 return grep($wt->[$_-1] != 0, MinLevel..$lv) ? TRUE : FALSE;
720 ## arrayref of arrayref[weights] source,
721 ## arrayref of arrayref[weights] substr,
723 ## * comparison of graphemes vs graphemes.
724 ## @$source >= @$substr must be true (check it before call this);
732 for my $g (0..@$substr-1){
733 # Do the $g'th graphemes have the same number of AV weigths?
734 return if @{ $source->[$g] } != @{ $substr->[$g] };
736 for my $w (0..@{ $substr->[$g] }-1) {
737 for my $v (0..$lev-1) {
738 return if $source->[$g][$w][$v] != $substr->[$g][$w][$v];
746 ## (int position, int length)
747 ## int position = index(string, substring, position, [undoc'ed grobal])
749 ## With "grobal" (only for the list context),
750 ## returns list of arrayref[position, length].
756 my $len = length($str);
757 my $subCE = $self->splitCE(shift);
758 my $pos = @_ ? shift : 0;
759 $pos = 0 if $pos < 0;
762 my $lev = $self->{level};
763 my $ver9 = $self->{UCA_Version} > 8;
764 my $v2i = $self->{alternate} ne 'non-ignorable';
767 my $temp = $pos <= 0 ? 0 : $len <= $pos ? $len : $pos;
769 ? map([$_, 0], $temp..$len)
770 : wantarray ? ($temp,0) : $temp;
773 return wantarray ? () : NOMATCHPOS;
775 my $strCE = $self->splitCE($pos ? substr($str, $pos) : $str, TRUE);
777 return wantarray ? () : NOMATCHPOS;
779 my $last_is_variable;
780 my(@strWt, @iniPos, @finPos, @subWt, @g_ret);
782 $last_is_variable = FALSE;
783 for my $wt (map $self->getWt($_), @$subCE) {
784 my $to_be_pushed = _nonIgnorAtLevel($wt,$lev);
788 $to_be_pushed = FALSE if $last_is_variable;
790 $last_is_variable = ($wt->[0] == Var1Wt);
794 if (@subWt && $wt->[0] == 0) {
795 push @{ $subWt[-1] }, $wt if $to_be_pushed;
797 $wt->[0] = 0 if $wt->[0] == Var1Wt;
798 push @subWt, [ $wt ];
803 my $end = @$strCE - 1;
805 $last_is_variable = FALSE;
807 for (my $i = 0; $i <= $end; ) { # no $i++
811 while ($i <= $end && $found_base == 0) {
812 for my $wt ($self->getWt($strCE->[$i][0])) {
813 my $to_be_pushed = _nonIgnorAtLevel($wt,$lev);
817 $to_be_pushed = FALSE if $last_is_variable;
819 $last_is_variable = ($wt->[0] == Var1Wt);
823 if (@strWt && $wt->[0] == 0) {
824 push @{ $strWt[-1] }, $wt if $to_be_pushed;
825 $finPos[-1] = $strCE->[$i][2];
826 } elsif ($to_be_pushed) {
827 $wt->[0] = 0 if $wt->[0] == Var1Wt;
828 push @strWt, [ $wt ];
829 push @iniPos, $found_base ? NOMATCHPOS : $strCE->[$i][1];
830 $finPos[-1] = NOMATCHPOS if $found_base;
831 push @finPos, $strCE->[$i][2];
840 while ( @strWt > @subWt || (@strWt == @subWt && $i > $end) ) {
841 if ($iniPos[0] != NOMATCHPOS &&
842 $finPos[$#subWt] != NOMATCHPOS &&
843 _eqArray(\@strWt, \@subWt, $lev)) {
844 my $temp = $iniPos[0] + $pos;
847 push @g_ret, [$temp, $finPos[$#subWt] - $iniPos[0]];
848 splice @strWt, 0, $#subWt;
849 splice @iniPos, 0, $#subWt;
850 splice @finPos, 0, $#subWt;
854 ? ($temp, $finPos[$#subWt] - $iniPos[0])
866 : wantarray ? () : NOMATCHPOS;
870 ## scalarref to matching part = match(string, substring)
875 if (my($pos,$len) = $self->index($_[0], $_[1])) {
876 my $temp = substr($_[0], $pos, $len);
877 return wantarray ? $temp : \$temp;
878 # An lvalue ref \substr should be avoided,
879 # since its value is affected by modification of its referent.
887 ## arrayref matching parts = gmatch(string, substring)
894 return map substr($str, $_->[0], $_->[1]),
895 $self->index($str, $sub, 0, 'g');
899 ## bool subst'ed = subst(string, substring, replace)
904 my $code = ref $_[2] eq 'CODE' ? $_[2] : FALSE;
906 if (my($pos,$len) = $self->index($_[0], $_[1])) {
908 my $mat = substr($_[0], $pos, $len);
909 substr($_[0], $pos, $len, $code->($mat));
911 substr($_[0], $pos, $len, $_[2]);
921 ## int count = gsubst(string, substring, replace)
926 my $code = ref $_[2] eq 'CODE' ? $_[2] : FALSE;
929 # Replacement is carried out from the end, then use reverse.
930 for my $pos_len (reverse $self->index($_[0], $_[1], 0, 'g')) {
932 my $mat = substr($_[0], $pos_len->[0], $pos_len->[1]);
933 substr($_[0], $pos_len->[0], $pos_len->[1], $code->($mat));
935 substr($_[0], $pos_len->[0], $pos_len->[1], $_[2]);
947 Unicode::Collate - Unicode Collation Algorithm
951 use Unicode::Collate;
954 $Collator = Unicode::Collate->new(%tailoring);
957 @sorted = $Collator->sort(@not_sorted);
960 $result = $Collator->cmp($a, $b); # returns 1, 0, or -1.
964 This module is an implementation
965 of Unicode Technical Standard #10 (UTS #10)
966 "Unicode Collation Algorithm."
968 =head2 Constructor and Tailoring
970 The C<new> method returns a collator object.
972 $Collator = Unicode::Collate->new(
973 UCA_Version => $UCA_Version,
974 alternate => $alternate,
975 backwards => $levelNumber, # or \@levelNumbers
977 normalization => $normalization_form,
978 ignoreName => qr/$ignoreName/,
979 ignoreChar => qr/$ignoreChar/,
980 katakana_before_hiragana => $bool,
981 level => $collationLevel,
982 overrideCJK => \&overrideCJK,
983 overrideHangul => \&overrideHangul,
984 preprocess => \&preprocess,
985 rearrange => \@charList,
987 undefName => qr/$undefName/,
988 undefChar => qr/$undefChar/,
989 upper_before_lower => $bool,
991 # if %tailoring is false (i.e. empty),
992 # $Collator should do the default collation.
998 If the version number of the older UCA is given,
999 the older behavior of that version is emulated on collating.
1000 If omitted, the return value of C<UCA_Version()> is used.
1002 The supported version: 8 or 9.
1004 B<This parameter may be removed in the future version,
1005 as switching the algorithm would affect the performance.>
1009 -- see 3.2.2 Variable Weighting, UTS #10.
1011 (the title in UCA version 8: Alternate Weighting)
1013 This key allows to alternate weighting for variable collation elements,
1014 which are marked with an ASTERISK in the table
1015 (NOTE: Many punction marks and symbols are variable in F<allkeys.txt>).
1017 alternate => 'blanked', 'non-ignorable', 'shifted', or 'shift-trimmed'.
1019 These names are case-insensitive.
1020 By default (if specification is omitted), 'shifted' is adopted.
1022 'Blanked' Variable elements are made ignorable at levels 1 through 3;
1023 considered at the 4th level.
1025 'Non-ignorable' Variable elements are not reset to ignorable.
1027 'Shifted' Variable elements are made ignorable at levels 1 through 3
1028 their level 4 weight is replaced by the old level 1 weight.
1029 Level 4 weight for Non-Variable elements is 0xFFFF.
1031 'Shift-Trimmed' Same as 'shifted', but all FFFF's at the 4th level
1036 -- see 3.1.2 French Accents, UTS #10.
1038 backwards => $levelNumber or \@levelNumbers
1040 Weights in reverse order; ex. level 2 (diacritic ordering) in French.
1041 If omitted, forwards at all the levels.
1045 -- see 3.1 Linguistic Features; 3.2.1 File Format, UTS #10.
1047 Overrides a default order or defines additional collation elements
1049 entry => <<'ENTRIES', # use the UCA file format
1050 00E6 ; [.0861.0020.0002.00E6] [.08B1.0020.0002.00E6] # ligature <ae> as <a><e>
1051 0063 0068 ; [.0893.0020.0002.0063] # "ch" in traditional Spanish
1052 0043 0068 ; [.0893.0020.0008.0043] # "Ch" in traditional Spanish
1055 B<NOTE:> The code point in the UCA file format (before C<';'>)
1056 B<must> be a Unicode code point, but not a native code point.
1057 So C<0063> must always denote C<U+0063>,
1058 but not a character of C<"\x63">.
1064 -- see Completely Ignorable, 3.2.2 Variable Weighting, UTS #10.
1066 Makes the entry in the table completely ignorable;
1067 i.e. as if the weights were zero at all level.
1069 E.g. when 'a' and 'e' are ignorable,
1070 'element' is equal to 'lament' (or 'lmnt').
1074 -- see 4.3 Form a sort key for each string, UTS #10.
1076 Set the maximum level.
1077 Any higher levels than the specified one are ignored.
1079 Level 1: alphabetic ordering
1080 Level 2: diacritic ordering
1081 Level 3: case ordering
1082 Level 4: tie-breaking (e.g. in the case when alternate is 'shifted')
1086 If omitted, the maximum is the 4th.
1090 -- see 4.1 Normalize each input string, UTS #10.
1092 If specified, strings are normalized before preparation of sort keys
1093 (the normalization is executed after preprocess).
1095 As a form name, one of the following names must be used.
1097 'C' or 'NFC' for Normalization Form C
1098 'D' or 'NFD' for Normalization Form D
1099 'KC' or 'NFKC' for Normalization Form KC
1100 'KD' or 'NFKD' for Normalization Form KD
1102 If omitted, the string is put into Normalization Form D.
1104 If C<undef> is passed explicitly as the value for this key,
1105 any normalization is not carried out (this may make tailoring easier
1106 if any normalization is not desired).
1112 -- see 7.1 Derived Collation Elements, UTS #10.
1114 By default, mapping of CJK Unified Ideographs
1115 uses the Unicode codepoint order.
1116 But the mapping of CJK Unified Ideographs may be overrided.
1118 ex. CJK Unified Ideographs in the JIS code point order.
1120 overrideCJK => sub {
1121 my $u = shift; # get a Unicode codepoint
1122 my $b = pack('n', $u); # to UTF-16BE
1123 my $s = your_unicode_to_sjis_converter($b); # convert
1124 my $n = unpack('n', $s); # convert sjis to short
1125 [ $n, 0x20, 0x2, $u ]; # return the collation element
1128 ex. ignores all CJK Unified Ideographs.
1130 overrideCJK => sub {()}, # CODEREF returning empty list
1132 # where ->eq("Pe\x{4E00}rl", "Perl") is true
1133 # as U+4E00 is a CJK Unified Ideograph and to be ignorable.
1135 If C<undef> is passed explicitly as the value for this key,
1136 weights for CJK Unified Ideographs are treated as undefined.
1137 But assignment of weight for CJK Unified Ideographs
1138 in table or L<entry> is still valid.
1140 =item overrideHangul
1142 -- see 7.1 Derived Collation Elements, UTS #10.
1144 By default, Hangul Syllables are decomposed into Hangul Jamo.
1145 But the mapping of Hangul Syllables may be overrided.
1147 This tag works like L<overrideCJK>, so see there for examples.
1149 If you want to override the mapping of Hangul Syllables,
1150 the Normalization Forms D and KD are not appropriate
1151 (they will be decomposed before overriding).
1153 If C<undef> is passed explicitly as the value for this key,
1154 weight for Hangul Syllables is treated as undefined
1155 without decomposition into Hangul Jamo.
1156 But definition of weight for Hangul Syllables
1157 in table or L<entry> is still valid.
1161 -- see 5.1 Preprocessing, UTS #10.
1163 If specified, the coderef is used to preprocess
1164 before the formation of sort keys.
1166 ex. dropping English articles, such as "a" or "the".
1167 Then, "the pen" is before "a pencil".
1171 $str =~ s/\b(?:an?|the)\s+//gi;
1177 -- see 3.1.3 Rearrangement, UTS #10.
1179 Characters that are not coded in logical order and to be rearranged.
1182 rearrange => [ 0x0E40..0x0E44, 0x0EC0..0x0EC4 ],
1184 If you want to disallow any rearrangement,
1185 pass C<undef> or C<[]> (a reference to an empty list)
1186 as the value for this key.
1188 B<According to the version 9 of UCA, this parameter shall not be used;
1189 but it is not warned at present.>
1193 -- see 3.2 Default Unicode Collation Element Table, UTS #10.
1195 You can use another element table if desired.
1196 The table file must be put into a directory
1197 where F<Unicode/Collate.pm> is installed.
1198 E.g. in F<perl/lib/Unicode/Collate> directory
1199 when you have F<perl/lib/Unicode/Collate.pm>.
1201 By default, the filename F<"allkeys.txt"> is used.
1203 If C<undef> is passed explicitly as the value for this key,
1204 no file is read (but you can define collation elements via L<entry>).
1206 A typical way to define a collation element table
1207 without any file of table:
1209 $onlyABC = Unicode::Collate->new(
1211 entry => << 'ENTRIES',
1212 0061 ; [.0101.0020.0002.0061] # LATIN SMALL LETTER A
1213 0041 ; [.0101.0020.0008.0041] # LATIN CAPITAL LETTER A
1214 0062 ; [.0102.0020.0002.0062] # LATIN SMALL LETTER B
1215 0042 ; [.0102.0020.0008.0042] # LATIN CAPITAL LETTER B
1216 0063 ; [.0103.0020.0002.0063] # LATIN SMALL LETTER C
1217 0043 ; [.0103.0020.0008.0043] # LATIN CAPITAL LETTER C
1225 -- see 6.3.4 Reducing the Repertoire, UTS #10.
1227 Undefines the collation element as if it were unassigned in the table.
1228 This reduces the size of the table.
1229 If an unassigned character appears in the string to be collated,
1230 the sort key is made from its codepoint
1231 as a single-character collation element,
1232 as it is greater than any other assigned collation elements
1233 (in the codepoint order among the unassigned characters).
1234 But, it'd be better to ignore characters
1235 unfamiliar to you and maybe never used.
1237 =item katakana_before_hiragana
1239 =item upper_before_lower
1241 -- see 6.6 Case Comparisons; 7.3.1 Tertiary Weight Table, UTS #10.
1243 By default, lowercase is before uppercase
1244 and hiragana is before katakana.
1246 If the tag is made true, this is reversed.
1248 B<NOTE>: These tags simplemindedly assume
1249 any lowercase/uppercase or hiragana/katakana distinctions
1250 must occur in level 3, and their weights at level 3
1251 must be same as those mentioned in 7.3.1, UTS #10.
1252 If you define your collation elements which violate this requirement,
1253 these tags don't work validly.
1257 =head2 Methods for Collation
1261 =item C<@sorted = $Collator-E<gt>sort(@not_sorted)>
1263 Sorts a list of strings.
1265 =item C<$result = $Collator-E<gt>cmp($a, $b)>
1267 Returns 1 (when C<$a> is greater than C<$b>)
1268 or 0 (when C<$a> is equal to C<$b>)
1269 or -1 (when C<$a> is lesser than C<$b>).
1271 =item C<$result = $Collator-E<gt>eq($a, $b)>
1273 =item C<$result = $Collator-E<gt>ne($a, $b)>
1275 =item C<$result = $Collator-E<gt>lt($a, $b)>
1277 =item C<$result = $Collator-E<gt>le($a, $b)>
1279 =item C<$result = $Collator-E<gt>gt($a, $b)>
1281 =item C<$result = $Collator-E<gt>ge($a, $b)>
1283 They works like the same name operators as theirs.
1285 eq : whether $a is equal to $b.
1286 ne : whether $a is not equal to $b.
1287 lt : whether $a is lesser than $b.
1288 le : whether $a is lesser than $b or equal to $b.
1289 gt : whether $a is greater than $b.
1290 ge : whether $a is greater than $b or equal to $b.
1292 =item C<$sortKey = $Collator-E<gt>getSortKey($string)>
1294 -- see 4.3 Form a sort key for each string, UTS #10.
1298 You compare the sort keys using a binary comparison
1299 and get the result of the comparison of the strings using UCA.
1301 $Collator->getSortKey($a) cmp $Collator->getSortKey($b)
1305 $Collator->cmp($a, $b)
1307 =item C<$sortKeyForm = $Collator-E<gt>viewSortKey($string)>
1309 use Unicode::Collate;
1310 my $c = Unicode::Collate->new();
1311 print $c->viewSortKey("Perl"),"\n";
1314 # [0B67 0A65 0B7F 0B03 | 0020 0020 0020 0020 | 0008 0002 0002 0002 | FFFF FFFF FFFF FFFF]
1315 # Level 1 Level 2 Level 3 Level 4
1317 (If C<UCA_Version> is 8, the output is slightly different.)
1321 =head2 Methods for Searching
1323 B<DISCLAIMER:> If C<preprocess> or C<normalization> tag is true
1324 for C<$Collator>, calling these methods (C<index>, C<match>, C<gmatch>,
1325 C<subst>, C<gsubst>) is croaked,
1326 as the position and the length might differ
1327 from those on the specified string.
1328 (And the C<rearrange> tag is neglected.)
1330 The C<match>, C<gmatch>, C<subst>, C<gsubst> methods work
1331 like C<m//>, C<m//g>, C<s///>, C<s///g>, respectively,
1332 but they are not aware of any pattern, but only a literal substring.
1336 =item C<$position = $Collator-E<gt>index($string, $substring[, $position])>
1338 =item C<($position, $length) = $Collator-E<gt>index($string, $substring[, $position])>
1340 If C<$substring> matches a part of C<$string>, returns
1341 the position of the first occurrence of the matching part in scalar context;
1342 in list context, returns a two-element list of
1343 the position and the length of the matching part.
1345 If C<$substring> does not match any part of C<$string>,
1346 returns C<-1> in scalar context and
1347 an empty list in list context.
1351 my $Collator = Unicode::Collate->new( normalization => undef, level => 1 );
1352 # (normalization => undef) is REQUIRED.
1353 my $str = "Ich muß studieren Perl.";
1356 if (my($pos,$len) = $Collator->index($str, $sub)) {
1357 $match = substr($str, $pos, $len);
1360 and get C<"muß"> in C<$match> since C<"muß">
1361 is primary equal to C<"MÜSS">.
1363 =item C<$match_ref = $Collator-E<gt>match($string, $substring)>
1365 =item C<($match) = $Collator-E<gt>match($string, $substring)>
1367 If C<$substring> matches a part of C<$string>, in scalar context, returns
1368 B<a reference to> the first occurrence of the matching part
1369 (C<$match_ref> is always true if matches,
1370 since every reference is B<true>);
1371 in list context, returns the first occurrence of the matching part.
1373 If C<$substring> does not match any part of C<$string>,
1374 returns C<undef> in scalar context and
1375 an empty list in list context.
1379 if ($match_ref = $Collator->match($str, $sub)) { # scalar context
1380 print "matches [$$match_ref].\n";
1382 print "doesn't match.\n";
1387 if (($match) = $Collator->match($str, $sub)) { # list context
1388 print "matches [$match].\n";
1390 print "doesn't match.\n";
1393 =item C<@match = $Collator-E<gt>gmatch($string, $substring)>
1395 If C<$substring> matches a part of C<$string>, returns
1396 all the matching parts (or matching count in scalar context).
1398 If C<$substring> does not match any part of C<$string>,
1399 returns an empty list.
1401 =item C<$count = $Collator-E<gt>subst($string, $substring, $replacement)>
1403 If C<$substring> matches a part of C<$string>,
1404 the first occurrence of the matching part is replaced by C<$replacement>
1405 (C<$string> is modified) and return C<$count> (always equals to C<1>).
1407 C<$replacement> can be a C<CODEREF>,
1408 taking the matching part as an argument,
1409 and returning a string to replace the matching part
1410 (a bit similar to C<s/(..)/$coderef-E<gt>($1)/e>).
1412 =item C<$count = $Collator-E<gt>gsubst($string, $substring, $replacement)>
1414 If C<$substring> matches a part of C<$string>,
1415 all the occurrences of the matching part is replaced by C<$replacement>
1416 (C<$string> is modified) and return C<$count>.
1418 C<$replacement> can be a C<CODEREF>,
1419 taking the matching part as an argument,
1420 and returning a string to replace the matching part
1421 (a bit similar to C<s/(..)/$coderef-E<gt>($1)/eg>).
1425 my $Collator = Unicode::Collate->new( normalization => undef, level => 1 );
1426 # (normalization => undef) is REQUIRED.
1427 my $str = "Camel ass came\x{301}l CAMEL horse cAm\0E\0L...";
1428 $Collator->gsubst($str, "camel", sub { "<b>$_[0]</b>" });
1430 # now $str is "<b>Camel</b> ass <b>came\x{301}l</b> <b>CAMEL</b> horse <b>cAm\0E\0L</b>...";
1431 # i.e., all the camels are made bold-faced.
1435 =head2 Other Methods
1439 =item C<%old_tailoring = $Collator-E<gt>change(%new_tailoring)>
1441 Change the value of specified keys and returns the changed part.
1443 $Collator = Unicode::Collate->new(level => 4);
1445 $Collator->eq("perl", "PERL"); # false
1447 %old = $Collator->change(level => 2); # returns (level => 4).
1449 $Collator->eq("perl", "PERL"); # true
1451 $Collator->change(%old); # returns (level => 2).
1453 $Collator->eq("perl", "PERL"); # false
1455 Not all C<(key,value)>s are allowed to be changed.
1456 See also C<@Unicode::Collate::ChangeOK> and C<@Unicode::Collate::ChangeNG>.
1458 In the scalar context, returns the modified collator
1459 (but it is B<not> a clone from the original).
1461 $Collator->change(level => 2)->eq("perl", "PERL"); # true
1463 $Collator->eq("perl", "PERL"); # true; now max level is 2nd.
1465 $Collator->change(level => 4)->eq("perl", "PERL"); # false
1469 Returns the version number of UTS #10 this module consults.
1471 =item Base_Unicode_Version
1473 Returns the version number of the Unicode Standard
1474 this module is based on.
1484 Use of the C<normalization> parameter requires
1485 the B<Unicode::Normalize> module.
1487 If you need not it (say, in the case when you need not
1488 handle any combining characters),
1489 assign C<normalization =E<gt> undef> explicitly.
1491 -- see 6.5 Avoiding Normalization, UTS #10.
1493 =head2 Conformance Test
1495 The Conformance Test for the UCA is provided
1496 in L<http://www.unicode.org/reports/tr10/CollationTest.html>
1497 and L<http://www.unicode.org/reports/tr10/CollationTest.zip>
1499 For F<CollationTest_SHIFTED.txt>,
1500 a collator via C<Unicode::Collate-E<gt>new( )> should be used;
1501 for F<CollationTest_NON_IGNORABLE.txt>, a collator via
1502 C<Unicode::Collate-E<gt>new(alternate =E<gt> "non-ignorable", level =E<gt> 3)>.
1504 B<Unicode::Normalize is required to try The Conformance Test.>
1508 SADAHIRO Tomoyuki, E<lt>SADAHIRO@cpan.orgE<gt>
1510 http://homepage1.nifty.com/nomenclator/perl/
1512 Copyright(C) 2001-2003, SADAHIRO Tomoyuki. Japan. All rights reserved.
1514 This library is free software; you can redistribute it
1515 and/or modify it under the same terms as Perl itself.
1521 =item http://www.unicode.org/reports/tr10/
1523 Unicode Collation Algorithm - UTS #10
1525 =item http://www.unicode.org/reports/tr10/allkeys.txt
1527 The Default Unicode Collation Element Table
1529 =item http://www.unicode.org/reports/tr10/CollationTest.html
1530 http://www.unicode.org/reports/tr10/CollationTest.zip
1532 The latest versions of the conformance test for the UCA
1534 =item http://www.unicode.org/reports/tr15/
1536 Unicode Normalization Forms - UAX #15
1538 =item L<Unicode::Normalize>