package Unicode::Collate;
BEGIN {
- if (ord("A") == 193) {
- die "Unicode::Collate not ported to EBCDIC\n";
+ unless ("A" eq pack('U', 0x41)) {
+ die "Unicode::Collate cannot stringify a Unicode code point\n";
}
}
use Carp;
use File::Spec;
-require Exporter;
+no warnings 'utf8';
-our $VERSION = '0.20';
+our $VERSION = '0.52';
our $PACKAGE = __PACKAGE__;
-our @ISA = qw(Exporter);
-
-our %EXPORT_TAGS = ();
-our @EXPORT_OK = ();
-our @EXPORT = ();
-
-(our $Path = $INC{'Unicode/Collate.pm'}) =~ s/\.pm$//;
-our $KeyFile = "allkeys.txt";
-
-our $UNICODE_VERSION;
-
-eval { require Unicode::UCD };
-
-unless ($@) {
- $UNICODE_VERSION = Unicode::UCD::UnicodeVersion();
-}
-else { # XXX, Perl 5.6.1
- my($f, $fh);
- foreach my $d (@INC) {
- $f = File::Spec->catfile($d, "unicode", "Unicode.301");
- if (open($fh, $f)) {
- $UNICODE_VERSION = '3.0.1';
- close $fh;
- last;
- }
- }
-}
-
-our $getCombinClass; # coderef for combining class from Unicode::Normalize
-
-use constant Min2 => 0x20; # minimum weight at level 2
-use constant Min3 => 0x02; # minimum weight at level 3
-
-# format for pack
-use constant VCE_FORMAT => 'Cn4'; # for variable + CE with 4 levels
-
-# values of variable
+my @Path = qw(Unicode Collate);
+my $KeyFile = "allkeys.txt";
+
+# Perl's boolean
+use constant TRUE => 1;
+use constant FALSE => "";
+use constant NOMATCHPOS => -1;
+
+# A coderef to get combining class imported from Unicode::Normalize
+# (i.e. \&Unicode::Normalize::getCombinClass).
+# This is also used as a HAS_UNICODE_NORMALIZE flag.
+my $CVgetCombinClass;
+
+# Supported Levels
+use constant MinLevel => 1;
+use constant MaxLevel => 4;
+
+# Minimum weights at level 2 and 3, respectively
+use constant Min2Wt => 0x20;
+use constant Min3Wt => 0x02;
+
+# Shifted weight at 4th level
+use constant Shift4Wt => 0xFFFF;
+
+# A boolean for Variable and 16-bit weights at 4 levels of Collation Element
+# PROBLEM: The Default Unicode Collation Element Table
+# has weights over 0xFFFF at the 4th level.
+# The tie-breaking in the variable weights
+# other than "shift" (as well as "shift-trimmed") is unreliable.
+use constant VCE_TEMPLATE => 'Cn4';
+
+# A sort key: 16-bit weights
+# See also the PROBLEM on VCE_TEMPLATE above.
+use constant KEY_TEMPLATE => 'n*';
+
+# Level separator in a sort key:
+# i.e. pack(KEY_TEMPLATE, 0)
+use constant LEVEL_SEP => "\0\0";
+
+# As Unicode code point separator for hash keys.
+# A joined code point string (denoted by JCPS below)
+# like "65;768" is used for internal processing
+# instead of Perl's Unicode string like "\x41\x{300}",
+# as the native code point is different from the Unicode code point
+# on EBCDIC platform.
+# This character must not be included in any stringified
+# representation of an integer.
+use constant CODE_SEP => ';';
+
+# boolean values of variable weights
use constant NON_VAR => 0; # Non-Variable character
use constant VAR => 1; # Variable character
-our $DefaultRearrange = [ 0x0E40..0x0E44, 0x0EC0..0x0EC4 ];
+# specific code points
+use constant Hangul_LBase => 0x1100;
+use constant Hangul_LIni => 0x1100;
+use constant Hangul_LFin => 0x1159;
+use constant Hangul_LFill => 0x115F;
+use constant Hangul_VBase => 0x1161;
+use constant Hangul_VIni => 0x1160; # from Vowel Filler
+use constant Hangul_VFin => 0x11A2;
+use constant Hangul_TBase => 0x11A7; # from "no-final" codepoint
+use constant Hangul_TIni => 0x11A8;
+use constant Hangul_TFin => 0x11F9;
+use constant Hangul_TCount => 28;
+use constant Hangul_NCount => 588;
+use constant Hangul_SBase => 0xAC00;
+use constant Hangul_SIni => 0xAC00;
+use constant Hangul_SFin => 0xD7A3;
+use constant CJK_UidIni => 0x4E00;
+use constant CJK_UidFin => 0x9FA5;
+use constant CJK_UidF41 => 0x9FBB;
+use constant CJK_ExtAIni => 0x3400;
+use constant CJK_ExtAFin => 0x4DB5;
+use constant CJK_ExtBIni => 0x20000;
+use constant CJK_ExtBFin => 0x2A6D6;
+use constant BMP_Max => 0xFFFF;
+
+# Logical_Order_Exception in PropList.txt
+my $DefaultRearrange = [ 0x0E40..0x0E44, 0x0EC0..0x0EC4 ];
+
+sub UCA_Version { "14" }
+
+sub Base_Unicode_Version { "4.1.0" }
+
+######
+
+sub pack_U {
+ return pack('U*', @_);
+}
-sub UCA_Version { "9" }
+sub unpack_U {
+ return unpack('U*', shift(@_).pack('U*'));
+}
-sub Base_Unicode_Version { $UNICODE_VERSION || 'unknown' }
+######
-my (%AlternateOK);
-@AlternateOK{ qw/
+my (%VariableOK);
+@VariableOK{ qw/
blanked non-ignorable shifted shift-trimmed
- / } = ();
+ / } = (); # keys lowercased
our @ChangeOK = qw/
alternate backwards level normalization rearrange
katakana_before_hiragana upper_before_lower
overrideHangul overrideCJK preprocess UCA_Version
+ hangul_terminator variable
/;
our @ChangeNG = qw/
- entry entries table ignored combining maxlength
- ignoreChar ignoreName undefChar undefName
+ entry mapping table maxlength
+ ignoreChar ignoreName undefChar undefName variableTable
versionTable alternateTable backwardsTable forwardsTable rearrangeTable
- derivCode normCode rearrangeHash isShift L3ignorable
+ derivCode normCode rearrangeHash
+ backwardsFlag
/;
+# The hash key 'ignored' is deleted at v 0.21.
+# The hash key 'isShift' is deleted at v 0.23.
+# The hash key 'combining' is deleted at v 0.24.
+# The hash key 'entries' is deleted at v 0.30.
+# The hash key 'L3_ignorable' is deleted at v 0.40.
+
+sub version {
+ my $self = shift;
+ return $self->{versionTable} || 'unknown';
+}
my (%ChangeOK, %ChangeNG);
@ChangeOK{ @ChangeOK } = ();
my $self = shift;
my %hash = @_;
my %old;
+ if (exists $hash{variable} && exists $hash{alternate}) {
+ delete $hash{alternate};
+ }
+ elsif (!exists $hash{variable} && exists $hash{alternate}) {
+ $hash{variable} = $hash{alternate};
+ }
foreach my $k (keys %hash) {
if (exists $ChangeOK{$k}) {
$old{$k} = $self->{$k};
}
# else => ignored
}
- $self->checkCollator;
+ $self->checkCollator();
return wantarray ? %old : $self;
}
+sub _checkLevel {
+ my $level = shift;
+ my $key = shift; # 'level' or 'backwards'
+ MinLevel <= $level or croak sprintf
+ "Illegal level %d (in value for key '%s') lower than %d.",
+ $level, $key, MinLevel;
+ $level <= MaxLevel or croak sprintf
+ "Unsupported level %d (in value for key '%s') higher than %d.",
+ $level, $key, MaxLevel;
+}
+
+my %DerivCode = (
+ 8 => \&_derivCE_8,
+ 9 => \&_derivCE_9,
+ 11 => \&_derivCE_9, # 11 == 9
+ 14 => \&_derivCE_14,
+);
+
sub checkCollator {
my $self = shift;
- croak "Illegal level lower than 1 (passed $self->{level})."
- if $self->{level} < 1;
- croak "A level higher than 4 (passed $self->{level}) is not supported."
- if 4 < $self->{level};
-
- $self->{derivCode} =
- $self->{UCA_Version} == -1 ? \&broken_derivCE :
- $self->{UCA_Version} == 8 ? \&derivCE_8 :
- $self->{UCA_Version} == 9 ? \&derivCE_9 :
- croak "Illegal UCA version (passed $self->{UCA_Version}).";
-
- $self->{alternate} = lc($self->{alternate});
- croak "$PACKAGE unknown alternate tag name: $self->{alternate}"
- unless exists $AlternateOK{ $self->{alternate} };
-
- $self->{isShift} = $self->{alternate} eq 'shifted' ||
- $self->{alternate} eq 'shift-trimmed';
-
- $self->{backwards} = []
- if ! defined $self->{backwards};
- $self->{backwards} = [ $self->{backwards} ]
- if ! ref $self->{backwards};
-
- $self->{rearrange} = []
- if ! defined $self->{rearrange};
- croak "$PACKAGE: A list for rearrangement must be store in an ARRAYREF"
- if ! ref $self->{rearrange};
+ _checkLevel($self->{level}, "level");
+
+ $self->{derivCode} = $DerivCode{ $self->{UCA_Version} }
+ or croak "Illegal UCA version (passed $self->{UCA_Version}).";
+
+ $self->{variable} ||= $self->{alternate} || $self->{variableTable} ||
+ $self->{alternateTable} || 'shifted';
+ $self->{variable} = $self->{alternate} = lc($self->{variable});
+ exists $VariableOK{ $self->{variable} }
+ or croak "$PACKAGE unknown variable parameter name: $self->{variable}";
+
+ if (! defined $self->{backwards}) {
+ $self->{backwardsFlag} = 0;
+ }
+ elsif (! ref $self->{backwards}) {
+ _checkLevel($self->{backwards}, "backwards");
+ $self->{backwardsFlag} = 1 << $self->{backwards};
+ }
+ else {
+ my %level;
+ $self->{backwardsFlag} = 0;
+ for my $b (@{ $self->{backwards} }) {
+ _checkLevel($b, "backwards");
+ $level{$b} = 1;
+ }
+ for my $v (sort keys %level) {
+ $self->{backwardsFlag} += 1 << $v;
+ }
+ }
+
+ defined $self->{rearrange} or $self->{rearrange} = [];
+ ref $self->{rearrange}
+ or croak "$PACKAGE: list for rearrangement must be store in ARRAYREF";
# keys of $self->{rearrangeHash} are $self->{rearrange}.
$self->{rearrangeHash} = undef;
if (defined $self->{normalization}) {
eval { require Unicode::Normalize };
- croak "Unicode/Normalize.pm is required to normalize strings: $@"
- if $@;
-
- Unicode::Normalize->import();
- $getCombinClass = \&Unicode::Normalize::getCombinClass
- if ! $getCombinClass;
-
- $self->{normCode} =
- $self->{normalization} =~ /^(?:NF)?C$/ ? \&NFC :
- $self->{normalization} =~ /^(?:NF)?D$/ ? \&NFD :
- $self->{normalization} =~ /^(?:NF)?KC$/ ? \&NFKC :
- $self->{normalization} =~ /^(?:NF)?KD$/ ? \&NFKD :
- croak "$PACKAGE unknown normalization form name: "
- . $self->{normalization};
+ $@ and croak "Unicode::Normalize is required to normalize strings";
+
+ $CVgetCombinClass ||= \&Unicode::Normalize::getCombinClass;
+
+ if ($self->{normalization} =~ /^(?:NF)D\z/) { # tweak for default
+ $self->{normCode} = \&Unicode::Normalize::NFD;
+ }
+ elsif ($self->{normalization} ne 'prenormalized') {
+ my $norm = $self->{normalization};
+ $self->{normCode} = sub {
+ Unicode::Normalize::normalize($norm, shift);
+ };
+ eval { $self->{normCode}->("") }; # try
+ $@ and croak "$PACKAGE unknown normalization form name: $norm";
+ }
}
return;
}
# If undef is passed explicitly, no file is read.
$self->{table} = $KeyFile if ! exists $self->{table};
- $self->read_table if defined $self->{table};
+ $self->read_table() if defined $self->{table};
if ($self->{entry}) {
- $self->parseEntry($_) foreach split /\n/, $self->{entry};
+ while ($self->{entry} =~ /([^\n]+)/g) {
+ $self->parseEntry($1);
+ }
}
- $self->{level} ||= 4;
+ $self->{level} ||= MaxLevel;
$self->{UCA_Version} ||= UCA_Version();
- $self->{overrideHangul} = ''
+ $self->{overrideHangul} = FALSE
if ! exists $self->{overrideHangul};
- $self->{overrideCJK} = ''
+ $self->{overrideCJK} = FALSE
if ! exists $self->{overrideCJK};
- $self->{normalization} = 'D'
+ $self->{normalization} = 'NFD'
if ! exists $self->{normalization};
- $self->{alternate} = $self->{alternateTable} || 'shifted'
- if ! exists $self->{alternate};
- $self->{rearrange} = $self->{rearrangeTable} || $DefaultRearrange
+ $self->{rearrange} = $self->{rearrangeTable} ||
+ ($self->{UCA_Version} <= 11 ? $DefaultRearrange : [])
if ! exists $self->{rearrange};
$self->{backwards} = $self->{backwardsTable}
if ! exists $self->{backwards};
- $self->checkCollator;
+ $self->checkCollator();
return $self;
}
sub read_table {
my $self = shift;
- my $file = $self->{table} ne '' ? $self->{table} : $KeyFile;
- my $filepath = File::Spec->catfile($Path, $file);
- open my $fk, "<$filepath"
- or croak "File does not exist at $filepath";
+ my($f, $fh);
+ foreach my $d (@INC) {
+ $f = File::Spec->catfile($d, @Path, $self->{table});
+ last if open($fh, $f);
+ $f = undef;
+ }
+ if (!defined $f) {
+ $f = File::Spec->catfile(@Path, $self->{table});
+ croak("$PACKAGE: Can't locate $f in \@INC (\@INC contains: @INC)");
+ }
- while (<$fk>) {
- next if /^\s*#/;
- if (/^\s*\@/) {
- if (/^\s*\@version\s*(\S*)/) {
- $self->{versionTable} ||= $1;
- }
- elsif (/^\s*\@alternate\s+(\S*)/) {
- $self->{alternateTable} ||= $1;
- }
- elsif (/^\s*\@backwards\s+(\S*)/) {
- push @{ $self->{backwardsTable} }, $1;
- }
- elsif (/^\s*\@forwards\s+(\S*)/) { # parhaps no use
- push @{ $self->{forwardsTable} }, $1;
- }
- elsif (/^\s*\@rearrange\s+(.*)/) { # (\S*) is NG
- push @{ $self->{rearrangeTable} }, _getHexArray($1);
- }
+ while (my $line = <$fh>) {
+ next if $line =~ /^\s*#/;
+ unless ($line =~ s/^\s*\@//) {
+ $self->parseEntry($line);
next;
}
- $self->parseEntry($_);
+
+ # matched ^\s*\@
+ if ($line =~ /^version\s*(\S*)/) {
+ $self->{versionTable} ||= $1;
+ }
+ elsif ($line =~ /^variable\s+(\S*)/) { # since UTS #10-9
+ $self->{variableTable} ||= $1;
+ }
+ elsif ($line =~ /^alternate\s+(\S*)/) { # till UTS #10-8
+ $self->{alternateTable} ||= $1;
+ }
+ elsif ($line =~ /^backwards\s+(\S*)/) {
+ push @{ $self->{backwardsTable} }, $1;
+ }
+ elsif ($line =~ /^forwards\s+(\S*)/) { # parhaps no use
+ push @{ $self->{forwardsTable} }, $1;
+ }
+ elsif ($line =~ /^rearrange\s+(.*)/) { # (\S*) is NG
+ push @{ $self->{rearrangeTable} }, _getHexArray($1);
+ }
}
- close $fk;
+ close $fh;
}
{
my $self = shift;
my $line = shift;
- my($name, $ele, @key);
+ my($name, $entry, @uv, @key);
return if $line !~ /^\s*[0-9A-Fa-f]/;
croak "Wrong Entry: <charList> must be separated by ';' from <collElement>"
if ! $k;
- my @e = _getHexArray($e);
- return if !@e;
+ @uv = _getHexArray($e);
+ return if !@uv;
+
+ $entry = join(CODE_SEP, @uv); # in JCPS
- $ele = pack('U*', @e);
- return if defined $self->{undefChar} && $ele =~ /$self->{undefChar}/;
+ if (defined $self->{undefChar} || defined $self->{ignoreChar}) {
+ my $ele = pack_U(@uv);
- # get sort key
- if (defined $self->{ignoreName} && $name =~ /$self->{ignoreName}/ ||
- defined $self->{ignoreChar} && $ele =~ /$self->{ignoreChar}/)
- {
- $self->{entries}{$ele} = $self->{ignored}{$ele} = 1;
+ # regarded as if it were not entried in the table
+ return
+ if defined $self->{undefChar} && $ele =~ /$self->{undefChar}/;
+
+ # replaced as completely ignorable
+ $k = '[.0000.0000.0000.0000]'
+ if defined $self->{ignoreChar} && $ele =~ /$self->{ignoreChar}/;
}
- else {
- my $combining = 1; # primary = 0, secondary != 0;
- my $level3ingore;
-
- foreach my $arr ($k =~ /\[([^\[\]]+)\]/g) { # SPACEs allowed
- my $var = $arr =~ /\*/; # exactly /^\*/ but be lenient.
- my @arr = _getHexArray($arr);
- push @key, pack(VCE_FORMAT, $var, @arr);
- $combining = 0 unless $arr[0] == 0 && $arr[1] != 0;
- $level3ingore = 1 if $arr[0] == 0 && $arr[1] == 0 && $arr[2] == 0;
- }
- $self->{entries}{$ele} = \@key;
- $self->{combining}{$ele} = 1
- if $combining;
+ # replaced as completely ignorable
+ $k = '[.0000.0000.0000.0000]'
+ if defined $self->{ignoreName} && $name =~ /$self->{ignoreName}/;
+
+ my $is_L3_ignorable = TRUE;
+
+ foreach my $arr ($k =~ /\[([^\[\]]+)\]/g) { # SPACEs allowed
+ my $var = $arr =~ /\*/; # exactly /^\*/ but be lenient.
+ my @wt = _getHexArray($arr);
+ push @key, pack(VCE_TEMPLATE, $var, @wt);
+ $is_L3_ignorable = FALSE
+ if $wt[0] || $wt[1] || $wt[2];
+ # Conformance Test for 3.1.1 and 4.0.0 shows Level 3 ignorable
+ # is completely ignorable.
+ # For expansion, an entry $is_L3_ignorable
+ # if and only if "all" CEs are [.0000.0000.0000].
+ }
+
+ $self->{mapping}{$entry} = $is_L3_ignorable ? [] : \@key;
- $self->{L3ignorable}{$e[0]} = 1
- if @e == 1 && $level3ingore;
+ if (@uv > 1) {
+ (!$self->{maxlength}{$uv[0]} || $self->{maxlength}{$uv[0]} < @uv)
+ and $self->{maxlength}{$uv[0]} = @uv;
}
- $self->{maxlength}{ord $ele} = scalar @e if @e > 1;
}
+
##
-## arrayref CE = altCE(bool variable?, list[num] weights)
+## VCE = _varCE(variable term, VCE)
##
-sub altCE
+sub _varCE
{
- my $self = shift;
- my($var, @c) = unpack(VCE_FORMAT, shift);
-
- $self->{alternate} eq 'blanked' ?
- $var ? [0,0,0,$c[3]] : \@c :
- $self->{alternate} eq 'non-ignorable' ?
- \@c :
- $self->{alternate} eq 'shifted' ?
- $var ? [0,0,0,$c[0] ] : [ @c[0..2], $c[0]+$c[1]+$c[2] ? 0xFFFF : 0 ] :
- $self->{alternate} eq 'shift-trimmed' ?
- $var ? [0,0,0,$c[0] ] : [ @c[0..2], 0 ] :
- croak "$PACKAGE unknown alternate name: $self->{alternate}";
+ my $vbl = shift;
+ my $vce = shift;
+ if ($vbl eq 'non-ignorable') {
+ return $vce;
+ }
+ my ($var, @wt) = unpack VCE_TEMPLATE, $vce;
+
+ if ($var) {
+ return pack(VCE_TEMPLATE, $var, 0, 0, 0,
+ $vbl eq 'blanked' ? $wt[3] : $wt[0]);
+ }
+ elsif ($vbl eq 'blanked') {
+ return $vce;
+ }
+ else {
+ return pack(VCE_TEMPLATE, $var, @wt[0..2],
+ $vbl eq 'shifted' && $wt[0]+$wt[1]+$wt[2] ? Shift4Wt : 0);
+ }
}
sub viewSortKey
{
my $self = shift;
- my $ver = $self->{UCA_Version};
+ $self->visualizeSortKey($self->getSortKey(@_));
+}
+
+sub visualizeSortKey
+{
+ my $self = shift;
+ my $view = join " ", map sprintf("%04X", $_), unpack(KEY_TEMPLATE, shift);
- my $key = $self->getSortKey(@_);
- my $view = join " ", map sprintf("%04X", $_), unpack 'n*', $key;
- if ($ver <= 8) {
+ if ($self->{UCA_Version} <= 8) {
$view =~ s/ ?0000 ?/|/g;
} else {
$view =~ s/\b0000\b/|/g;
##
-## list[strings] elements = splitCE(string arg)
+## arrayref of JCPS = splitEnt(string to be collated)
+## arrayref of arrayref[JCPS, ini_pos, fin_pos] = splitEnt(string, true)
##
-sub splitCE
+sub splitEnt
{
my $self = shift;
+ my $wLen = $_[1];
+
my $code = $self->{preprocess};
my $norm = $self->{normCode};
- my $ent = $self->{entries};
+ my $map = $self->{mapping};
my $max = $self->{maxlength};
my $reH = $self->{rearrangeHash};
- my $L3i = $self->{L3ignorable};
- my $ver9 = $self->{UCA_Version} > 8;
+ my $ver9 = $self->{UCA_Version} >= 9 && $self->{UCA_Version} <= 11;
- my $str = ref $code ? &$code(shift) : shift;
- $str = &$norm($str) if ref $norm;
+ my ($str, @buf);
+
+ if ($wLen) {
+ $code and croak "Preprocess breaks character positions. "
+ . "Don't use with index(), match(), etc.";
+ $norm and croak "Normalization breaks character positions. "
+ . "Don't use with index(), match(), etc.";
+ $str = $_[0];
+ }
+ else {
+ $str = $_[0];
+ $str = &$code($str) if ref $code;
+ $str = &$norm($str) if ref $norm;
+ }
- my @src = unpack('U*', $str);
- my @buf;
+ # get array of Unicode code point of string.
+ my @src = unpack_U($str);
- # rearrangement
- if ($reH) {
+ # rearrangement:
+ # Character positions are not kept if rearranged,
+ # then neglected if $wLen is true.
+ if ($reH && ! $wLen) {
for (my $i = 0; $i < @src; $i++) {
if (exists $reH->{ $src[$i] } && $i + 1 < @src) {
($src[$i], $src[$i+1]) = ($src[$i+1], $src[$i]);
}
}
- if ($ver9) {
- @src = grep ! $L3i->{$_}, @src;
+ # remove a code point marked as a completely ignorable.
+ for (my $i = 0; $i < @src; $i++) {
+ $src[$i] = undef
+ if _isIllegal($src[$i]) || ($ver9 &&
+ $map->{ $src[$i] } && @{ $map->{ $src[$i] } } == 0);
}
for (my $i = 0; $i < @src; $i++) {
- my $ch;
- my $u = $src[$i];
-
- # non-characters
- next unless defined $u;
- next if $u < 0 || 0x10FFFF < $u # out of range
- || (0xD800 <= $u && $u <= 0xDFFF) # unpaired surrogates
- || (0xFDD0 <= $u && $u <= 0xFDEF) # non-character
- ;
-
- my $four = $u & 0xFFFF;
- next if $four == 0xFFFE || $four == 0xFFFF;
-
- if ($max->{$u}) { # contract
- for (my $j = $max->{$u}; $j >= 1; $j--) {
- next unless $i+$j-1 < @src;
- $ch = pack 'U*', @src[$i .. $i+$j-1];
- $i += $j-1, last if $ent->{$ch};
+ my $jcps = $src[$i];
+
+ # skip removed code point
+ if (! defined $jcps) {
+ if ($wLen && @buf) {
+ $buf[-1][2] = $i + 1;
+ }
+ next;
+ }
+
+ my $i_orig = $i;
+
+ # find contraction
+ if ($max->{$jcps}) {
+ my $temp_jcps = $jcps;
+ my $jcpsLen = 1;
+ my $maxLen = $max->{$jcps};
+
+ for (my $p = $i + 1; $jcpsLen < $maxLen && $p < @src; $p++) {
+ next if ! defined $src[$p];
+ $temp_jcps .= CODE_SEP . $src[$p];
+ $jcpsLen++;
+ if ($map->{$temp_jcps}) {
+ $jcps = $temp_jcps;
+ $i = $p;
+ }
+ }
+
+ # not-contiguous contraction with Combining Char (cf. UTS#10, S2.1).
+ # This process requires Unicode::Normalize.
+ # If "normalization" is undef, here should be skipped *always*
+ # (in spite of bool value of $CVgetCombinClass),
+ # since canonical ordering cannot be expected.
+ # Blocked combining character should not be contracted.
+
+ if ($self->{normalization})
+ # $self->{normCode} is false in the case of "prenormalized".
+ {
+ my $preCC = 0;
+ my $curCC = 0;
+
+ for (my $p = $i + 1; $p < @src; $p++) {
+ next if ! defined $src[$p];
+ $curCC = $CVgetCombinClass->($src[$p]);
+ last unless $curCC;
+ my $tail = CODE_SEP . $src[$p];
+ if ($preCC != $curCC && $map->{$jcps.$tail}) {
+ $jcps .= $tail;
+ $src[$p] = undef;
+ } else {
+ $preCC = $curCC;
+ }
+ }
}
- } else {
- $ch = pack('U', $u);
}
- # with Combining Char (UTS#10, 4.2.1), here requires Unicode::Normalize.
- if ($getCombinClass && defined $ch) {
- for (my $j = $i+1; $j < @src; $j++) {
- next unless defined $src[$j];
- last unless $getCombinClass->( $src[$j] );
- my $comb = pack 'U', $src[$j];
- next if ! $ent->{ $ch.$comb };
- $ch .= $comb;
- $src[$j] = undef;
+ # skip completely ignorable
+ if ($map->{$jcps} && @{ $map->{$jcps} } == 0) {
+ if ($wLen && @buf) {
+ $buf[-1][2] = $i + 1;
}
+ next;
}
- push @buf, $ch;
+
+ push @buf, $wLen ? [$jcps, $i_orig, $i + 1] : $jcps;
}
- wantarray ? @buf : \@buf;
+ return \@buf;
}
##
-## list[arrayrefs] weight = getWt(string element)
+## list of VCE = getWt(JCPS)
##
sub getWt
{
my $self = shift;
- my $ch = shift;
- my $ent = $self->{entries};
- my $ign = $self->{ignored};
- my $cjk = $self->{overrideCJK};
- my $hang = $self->{overrideHangul};
+ my $u = shift;
+ my $vbl = $self->{variable};
+ my $map = $self->{mapping};
my $der = $self->{derivCode};
- return if !defined $ch || $ign->{$ch}; # ignored
- return map($self->altCE($_), @{ $ent->{$ch} })
- if $ent->{$ch};
-
- my $u = unpack('U', $ch);
-
- if (0xAC00 <= $u && $u <= 0xD7A3) { # is_Hangul
- return map $self->altCE($_),
- $hang
- ? map(pack(VCE_FORMAT, NON_VAR, @$_), &$hang($u))
- : defined $hang
- ? map({
- my $v = $_;
- my $vCE = $ent->{pack('U', $v)};
- $vCE ? @$vCE : $der->($v);
- } _decompHangul($u))
- : $der->($u);
+ return if !defined $u;
+ return map(_varCE($vbl, $_), @{ $map->{$u} })
+ if $map->{$u};
+
+ # JCPS must not be a contraction, then it's a code point.
+ if (Hangul_SIni <= $u && $u <= Hangul_SFin) {
+ my $hang = $self->{overrideHangul};
+ my @hangulCE;
+ if ($hang) {
+ @hangulCE = map(pack(VCE_TEMPLATE, NON_VAR, @$_), &$hang($u));
+ }
+ elsif (!defined $hang) {
+ @hangulCE = $der->($u);
+ }
+ else {
+ my $max = $self->{maxlength};
+ my @decH = _decompHangul($u);
+
+ if (@decH == 2) {
+ my $contract = join(CODE_SEP, @decH);
+ @decH = ($contract) if $map->{$contract};
+ } else { # must be <@decH == 3>
+ if ($max->{$decH[0]}) {
+ my $contract = join(CODE_SEP, @decH);
+ if ($map->{$contract}) {
+ @decH = ($contract);
+ } else {
+ $contract = join(CODE_SEP, @decH[0,1]);
+ $map->{$contract} and @decH = ($contract, $decH[2]);
+ }
+ # even if V's ignorable, LT contraction is not supported.
+ # If such a situatution were required, NFD should be used.
+ }
+ if (@decH == 3 && $max->{$decH[1]}) {
+ my $contract = join(CODE_SEP, @decH[1,2]);
+ $map->{$contract} and @decH = ($decH[0], $contract);
+ }
+ }
+
+ @hangulCE = map({
+ $map->{$_} ? @{ $map->{$_} } : $der->($_);
+ } @decH);
+ }
+ return map _varCE($vbl, $_), @hangulCE;
}
- elsif (0x3400 <= $u && $u <= 0x4DB5 ||
- 0x4E00 <= $u && $u <= 0x9FA5 ||
- 0x20000 <= $u && $u <= 0x2A6D6) { # CJK Ideograph
- return map $self->altCE($_),
+ elsif (_isUIdeo($u, $self->{UCA_Version})) {
+ my $cjk = $self->{overrideCJK};
+ return map _varCE($vbl, $_),
$cjk
- ? map(pack(VCE_FORMAT, NON_VAR, @$_), &$cjk($u))
+ ? map(pack(VCE_TEMPLATE, NON_VAR, @$_), &$cjk($u))
: defined $cjk && $self->{UCA_Version} <= 8 && $u < 0x10000
- ? pack(VCE_FORMAT, NON_VAR, $u, 0x20, 0x02, $u)
+ ? _uideoCE_8($u)
: $der->($u);
}
else {
- return map $self->altCE($_), $der->($u);
+ return map _varCE($vbl, $_), $der->($u);
}
}
+
##
-## int = index(string, substring)
+## string sortkey = getSortKey(string arg)
##
-sub index
+sub getSortKey
{
my $self = shift;
my $lev = $self->{level};
- my $comb = $self->{combining};
- my $str = $self->splitCE(shift);
- my $sub = $self->splitCE(shift);
-
- return wantarray ? (0,0) : 0 if ! @$sub;
- return wantarray ? () : -1 if ! @$str;
-
- my @subWt = grep _ignorableAtLevel($_,$lev),
- map $self->getWt($_), @$sub;
-
- my(@strWt,@strPt);
- my $count = 0;
- for (my $i = 0; $i < @$str; $i++) {
- my $go_ahead = 0;
-
- my @tmp = grep _ignorableAtLevel($_,$lev), $self->getWt($str->[$i]);
- $go_ahead += length $str->[$i];
-
- # /*XXX*/ still broken.
- # index("e\x{300}", "e") should be 'no match' at level 2 or higher
- # as "e\x{300}" is a *single* grapheme cluster and not equal to "e".
-
- # go ahead as far as we find a combining character;
- while ($i + 1 < @$str &&
- (! defined $str->[$i+1] || $comb->{ $str->[$i+1] }) ) {
- $i++;
- next if ! defined $str->[$i];
- $go_ahead += length $str->[$i];
- push @tmp,
- grep _ignorableAtLevel($_,$lev), $self->getWt($str->[$i]);
- }
-
- push @strWt, @tmp;
- push @strPt, ($count) x @tmp;
- $count += $go_ahead;
+ my $rEnt = $self->splitEnt(shift); # get an arrayref of JCPS
+ my $v2i = $self->{UCA_Version} >= 9 &&
+ $self->{variable} ne 'non-ignorable';
+
+ my @buf; # weight arrays
+ if ($self->{hangul_terminator}) {
+ my $preHST = '';
+ foreach my $jcps (@$rEnt) {
+ # weird things like VL, TL-contraction are not considered!
+ my $curHST = '';
+ foreach my $u (split /;/, $jcps) {
+ $curHST .= getHST($u);
+ }
+ if ($preHST && !$curHST || # hangul before non-hangul
+ $preHST =~ /L\z/ && $curHST =~ /^T/ ||
+ $preHST =~ /V\z/ && $curHST =~ /^L/ ||
+ $preHST =~ /T\z/ && $curHST =~ /^[LV]/) {
- while (@strWt >= @subWt) {
- if (_eqArray(\@strWt, \@subWt, $lev)) {
- my $pos = $strPt[0];
- return wantarray ? ($pos, $count-$pos) : $pos;
+ push @buf, $self->getWtHangulTerm();
}
- shift @strWt;
- shift @strPt;
+ $preHST = $curHST;
+
+ push @buf, $self->getWt($jcps);
}
+ $preHST # end at hangul
+ and push @buf, $self->getWtHangulTerm();
}
- return wantarray ? () : -1;
-}
-
-##
-## bool _eqArray(arrayref, arrayref, level)
-##
-sub _eqArray($$$)
-{
- my $a = shift; # length $a >= length $b;
- my $b = shift;
- my $lev = shift;
- for my $v (0..$lev-1) {
- for my $c (0..@$b-1){
- return if $a->[$c][$v] != $b->[$c][$v];
+ else {
+ foreach my $jcps (@$rEnt) {
+ push @buf, $self->getWt($jcps);
}
}
- return 1;
-}
-
-##
-## bool _ignorableAtLevel(CE, level)
-##
-sub _ignorableAtLevel($$)
-{
- my $ce = shift;
- return unless defined $ce;
- my $lv = shift;
- return ! grep { ! $ce->[$_] } 0..$lv-1;
-}
+ # make sort key
+ my @ret = ([],[],[],[]);
+ my $last_is_variable;
+ foreach my $vwt (@buf) {
+ my($var, @wt) = unpack(VCE_TEMPLATE, $vwt);
-##
-## string sortkey = getSortKey(string arg)
-##
-sub getSortKey
-{
- my $self = shift;
- my $lev = $self->{level};
- my $rCE = $self->splitCE(shift); # get an arrayref
- my $ver9 = $self->{UCA_Version} > 8;
- my $sht = $self->{isShift};
-
- # weight arrays
- my (@buf, $last_is_variable);
-
- foreach my $ce (@$rCE) {
- my @t = $self->getWt($ce);
- if ($sht && $ver9) {
- if (@t == 1 && $t[0][0] == 0) {
- if ($t[0][1] == 0 && $t[0][2] == 0) {
- $last_is_variable = 1;
- } else {
- next if $last_is_variable;
- }
- } else {
- $last_is_variable = 0;
+ # "Ignorable (L1, L2) after Variable" since track. v. 9
+ if ($v2i) {
+ if ($var) {
+ $last_is_variable = TRUE;
+ }
+ elsif (!$wt[0]) { # ignorable
+ next if $last_is_variable;
+ }
+ else {
+ $last_is_variable = FALSE;
}
}
- push @buf, @t;
- }
-
- # make sort key
- my @ret = ([],[],[],[]);
- foreach my $v (0..$lev-1) {
- foreach my $b (@buf) {
- push @{ $ret[$v] }, $b->[$v] if $b->[$v];
+ foreach my $v (0..$lev-1) {
+ 0 < $wt[$v] and push @{ $ret[$v] }, $wt[$v];
}
}
- foreach (@{ $self->{backwards} }) {
- my $v = $_ - 1;
- @{ $ret[$v] } = reverse @{ $ret[$v] };
- }
# modification of tertiary weights
if ($self->{upper_before_lower}) {
- foreach (@{ $ret[2] }) {
- if (0x8 <= $_ && $_ <= 0xC) { $_ -= 6 } # lower
- elsif (0x2 <= $_ && $_ <= 0x6) { $_ += 6 } # upper
- elsif ($_ == 0x1C) { $_ += 1 } # square upper
- elsif ($_ == 0x1D) { $_ -= 1 } # square lower
+ foreach my $w (@{ $ret[2] }) {
+ if (0x8 <= $w && $w <= 0xC) { $w -= 6 } # lower
+ elsif (0x2 <= $w && $w <= 0x6) { $w += 6 } # upper
+ elsif ($w == 0x1C) { $w += 1 } # square upper
+ elsif ($w == 0x1D) { $w -= 1 } # square lower
}
}
if ($self->{katakana_before_hiragana}) {
- foreach (@{ $ret[2] }) {
- if (0x0F <= $_ && $_ <= 0x13) { $_ -= 2 } # katakana
- elsif (0x0D <= $_ && $_ <= 0x0E) { $_ += 5 } # hiragana
+ foreach my $w (@{ $ret[2] }) {
+ if (0x0F <= $w && $w <= 0x13) { $w -= 2 } # katakana
+ elsif (0x0D <= $w && $w <= 0x0E) { $w += 5 } # hiragana
+ }
+ }
+
+ if ($self->{backwardsFlag}) {
+ for (my $v = MinLevel; $v <= MaxLevel; $v++) {
+ if ($self->{backwardsFlag} & (1 << $v)) {
+ @{ $ret[$v-1] } = reverse @{ $ret[$v-1] };
+ }
}
}
- join "\0\0", map pack('n*', @$_), @ret;
+
+ join LEVEL_SEP, map pack(KEY_TEMPLATE, @$_), @ret;
}
}
-sub derivCE_9 {
+sub _derivCE_14 {
my $u = shift;
my $base =
- (0x4E00 <= $u && $u <= 0x9FA5) # CJK
- ? 0xFB40 :
- (0x3400 <= $u && $u <= 0x4DB5 || 0x20000 <= $u && $u <= 0x2A6D6)
- ? 0xFB80 : 0xFBC0;
+ (CJK_UidIni <= $u && $u <= CJK_UidF41)
+ ? 0xFB40 : # CJK
+ (CJK_ExtAIni <= $u && $u <= CJK_ExtAFin ||
+ CJK_ExtBIni <= $u && $u <= CJK_ExtBFin)
+ ? 0xFB80 # CJK ext.
+ : 0xFBC0; # others
my $aaaa = $base + ($u >> 15);
my $bbbb = ($u & 0x7FFF) | 0x8000;
return
- pack(VCE_FORMAT, NON_VAR, $aaaa, Min2, Min3, $u),
- pack(VCE_FORMAT, NON_VAR, $bbbb, 0, 0, $u);
+ pack(VCE_TEMPLATE, NON_VAR, $aaaa, Min2Wt, Min3Wt, $u),
+ pack(VCE_TEMPLATE, NON_VAR, $bbbb, 0, 0, $u);
}
-sub derivCE_8 {
+sub _derivCE_9 {
+ my $u = shift;
+ my $base =
+ (CJK_UidIni <= $u && $u <= CJK_UidFin)
+ ? 0xFB40 : # CJK
+ (CJK_ExtAIni <= $u && $u <= CJK_ExtAFin ||
+ CJK_ExtBIni <= $u && $u <= CJK_ExtBFin)
+ ? 0xFB80 # CJK ext.
+ : 0xFBC0; # others
+
+ my $aaaa = $base + ($u >> 15);
+ my $bbbb = ($u & 0x7FFF) | 0x8000;
+ return
+ pack(VCE_TEMPLATE, NON_VAR, $aaaa, Min2Wt, Min3Wt, $u),
+ pack(VCE_TEMPLATE, NON_VAR, $bbbb, 0, 0, $u);
+}
+
+sub _derivCE_8 {
my $code = shift;
my $aaaa = 0xFF80 + ($code >> 15);
my $bbbb = ($code & 0x7FFF) | 0x8000;
return
- pack(VCE_FORMAT, NON_VAR, $aaaa, 2, 1, $code),
- pack(VCE_FORMAT, NON_VAR, $bbbb, 0, 0, $code);
+ pack(VCE_TEMPLATE, NON_VAR, $aaaa, 2, 1, $code),
+ pack(VCE_TEMPLATE, NON_VAR, $bbbb, 0, 0, $code);
}
-sub broken_derivCE { # NG
- my $code = shift;
- my $aaaa = 0xFFC2 + ($code >> 15);
- my $bbbb = $code & 0x7FFF | 0x1000;
- return
- pack(VCE_FORMAT, NON_VAR, $aaaa, 2, 1, $code),
- pack(VCE_FORMAT, NON_VAR, $bbbb, 0, 0, $code);
+sub _uideoCE_8 {
+ my $u = shift;
+ return pack(VCE_TEMPLATE, NON_VAR, $u, Min2Wt, Min3Wt, $u);
}
+sub _isUIdeo {
+ my ($u, $uca_vers) = @_;
+ return(
+ (CJK_UidIni <= $u &&
+ ($uca_vers >= 14 ? ( $u <= CJK_UidF41) : ($u <= CJK_UidFin)))
+ ||
+ (CJK_ExtAIni <= $u && $u <= CJK_ExtAFin)
+ ||
+ (CJK_ExtBIni <= $u && $u <= CJK_ExtBFin)
+ );
+}
+
+
+sub getWtHangulTerm {
+ my $self = shift;
+ return _varCE($self->{variable},
+ pack(VCE_TEMPLATE, NON_VAR, $self->{hangul_terminator}, 0,0,0));
+}
+
+
##
## "hhhh hhhh hhhh" to (dddd, dddd, dddd)
##
sub _getHexArray { map hex, $_[0] =~ /([0-9a-fA-F]+)/g }
#
-# $code must be in Hangul syllable.
+# $code *must* be in Hangul syllable.
# Check it before you enter here.
#
sub _decompHangul {
my $code = shift;
- my $SIndex = $code - 0xAC00;
- my $LIndex = int( $SIndex / 588);
- my $VIndex = int(($SIndex % 588) / 28);
- my $TIndex = $SIndex % 28;
+ my $si = $code - Hangul_SBase;
+ my $li = int( $si / Hangul_NCount);
+ my $vi = int(($si % Hangul_NCount) / Hangul_TCount);
+ my $ti = $si % Hangul_TCount;
return (
- 0x1100 + $LIndex,
- 0x1161 + $VIndex,
- $TIndex ? (0x11A7 + $TIndex) : (),
+ Hangul_LBase + $li,
+ Hangul_VBase + $vi,
+ $ti ? (Hangul_TBase + $ti) : (),
);
}
+sub _isIllegal {
+ my $code = shift;
+ return ! defined $code # removed
+ || ($code < 0 || 0x10FFFF < $code) # out of range
+ || (($code & 0xFFFE) == 0xFFFE) # ??FFF[EF] (cf. utf8.c)
+ || (0xD800 <= $code && $code <= 0xDFFF) # unpaired surrogates
+ || (0xFDD0 <= $code && $code <= 0xFDEF) # other non-characters
+ ;
+}
+
+# Hangul Syllable Type
+sub getHST {
+ my $u = shift;
+ return
+ Hangul_LIni <= $u && $u <= Hangul_LFin || $u == Hangul_LFill ? "L" :
+ Hangul_VIni <= $u && $u <= Hangul_VFin ? "V" :
+ Hangul_TIni <= $u && $u <= Hangul_TFin ? "T" :
+ Hangul_SIni <= $u && $u <= Hangul_SFin ?
+ ($u - Hangul_SBase) % Hangul_TCount ? "LVT" : "LV" : "";
+}
+
+
+##
+## bool _nonIgnorAtLevel(arrayref weights, int level)
+##
+sub _nonIgnorAtLevel($$)
+{
+ my $wt = shift;
+ return if ! defined $wt;
+ my $lv = shift;
+ return grep($wt->[$_-1] != 0, MinLevel..$lv) ? TRUE : FALSE;
+}
+
+##
+## bool _eqArray(
+## arrayref of arrayref[weights] source,
+## arrayref of arrayref[weights] substr,
+## int level)
+## * comparison of graphemes vs graphemes.
+## @$source >= @$substr must be true (check it before call this);
+##
+sub _eqArray($$$)
+{
+ my $source = shift;
+ my $substr = shift;
+ my $lev = shift;
+
+ for my $g (0..@$substr-1){
+ # Do the $g'th graphemes have the same number of AV weigths?
+ return if @{ $source->[$g] } != @{ $substr->[$g] };
+
+ for my $w (0..@{ $substr->[$g] }-1) {
+ for my $v (0..$lev-1) {
+ return if $source->[$g][$w][$v] != $substr->[$g][$w][$v];
+ }
+ }
+ }
+ return 1;
+}
+
+##
+## (int position, int length)
+## int position = index(string, substring, position, [undoc'ed grobal])
+##
+## With "grobal" (only for the list context),
+## returns list of arrayref[position, length].
+##
+sub index
+{
+ my $self = shift;
+ my $str = shift;
+ my $len = length($str);
+ my $subE = $self->splitEnt(shift);
+ my $pos = @_ ? shift : 0;
+ $pos = 0 if $pos < 0;
+ my $grob = shift;
+
+ my $lev = $self->{level};
+ my $v2i = $self->{UCA_Version} >= 9 &&
+ $self->{variable} ne 'non-ignorable';
+
+ if (! @$subE) {
+ my $temp = $pos <= 0 ? 0 : $len <= $pos ? $len : $pos;
+ return $grob
+ ? map([$_, 0], $temp..$len)
+ : wantarray ? ($temp,0) : $temp;
+ }
+ $len < $pos
+ and return wantarray ? () : NOMATCHPOS;
+ my $strE = $self->splitEnt($pos ? substr($str, $pos) : $str, TRUE);
+ @$strE
+ or return wantarray ? () : NOMATCHPOS;
+
+ my(@strWt, @iniPos, @finPos, @subWt, @g_ret);
+
+ my $last_is_variable;
+ for my $vwt (map $self->getWt($_), @$subE) {
+ my($var, @wt) = unpack(VCE_TEMPLATE, $vwt);
+ my $to_be_pushed = _nonIgnorAtLevel(\@wt,$lev);
+
+ # "Ignorable (L1, L2) after Variable" since track. v. 9
+ if ($v2i) {
+ if ($var) {
+ $last_is_variable = TRUE;
+ }
+ elsif (!$wt[0]) { # ignorable
+ $to_be_pushed = FALSE if $last_is_variable;
+ }
+ else {
+ $last_is_variable = FALSE;
+ }
+ }
+
+ if (@subWt && !$var && !$wt[0]) {
+ push @{ $subWt[-1] }, \@wt if $to_be_pushed;
+ } else {
+ push @subWt, [ \@wt ];
+ }
+ }
+
+ my $count = 0;
+ my $end = @$strE - 1;
+
+ $last_is_variable = FALSE; # reuse
+ for (my $i = 0; $i <= $end; ) { # no $i++
+ my $found_base = 0;
+
+ # fetch a grapheme
+ while ($i <= $end && $found_base == 0) {
+ for my $vwt ($self->getWt($strE->[$i][0])) {
+ my($var, @wt) = unpack(VCE_TEMPLATE, $vwt);
+ my $to_be_pushed = _nonIgnorAtLevel(\@wt,$lev);
+
+ # "Ignorable (L1, L2) after Variable" since track. v. 9
+ if ($v2i) {
+ if ($var) {
+ $last_is_variable = TRUE;
+ }
+ elsif (!$wt[0]) { # ignorable
+ $to_be_pushed = FALSE if $last_is_variable;
+ }
+ else {
+ $last_is_variable = FALSE;
+ }
+ }
+
+ if (@strWt && !$var && !$wt[0]) {
+ push @{ $strWt[-1] }, \@wt if $to_be_pushed;
+ $finPos[-1] = $strE->[$i][2];
+ } elsif ($to_be_pushed) {
+ push @strWt, [ \@wt ];
+ push @iniPos, $found_base ? NOMATCHPOS : $strE->[$i][1];
+ $finPos[-1] = NOMATCHPOS if $found_base;
+ push @finPos, $strE->[$i][2];
+ $found_base++;
+ }
+ # else ===> no-op
+ }
+ $i++;
+ }
+
+ # try to match
+ while ( @strWt > @subWt || (@strWt == @subWt && $i > $end) ) {
+ if ($iniPos[0] != NOMATCHPOS &&
+ $finPos[$#subWt] != NOMATCHPOS &&
+ _eqArray(\@strWt, \@subWt, $lev)) {
+ my $temp = $iniPos[0] + $pos;
+
+ if ($grob) {
+ push @g_ret, [$temp, $finPos[$#subWt] - $iniPos[0]];
+ splice @strWt, 0, $#subWt;
+ splice @iniPos, 0, $#subWt;
+ splice @finPos, 0, $#subWt;
+ }
+ else {
+ return wantarray
+ ? ($temp, $finPos[$#subWt] - $iniPos[0])
+ : $temp;
+ }
+ }
+ shift @strWt;
+ shift @iniPos;
+ shift @finPos;
+ }
+ }
+
+ return $grob
+ ? @g_ret
+ : wantarray ? () : NOMATCHPOS;
+}
+
+##
+## scalarref to matching part = match(string, substring)
+##
+sub match
+{
+ my $self = shift;
+ if (my($pos,$len) = $self->index($_[0], $_[1])) {
+ my $temp = substr($_[0], $pos, $len);
+ return wantarray ? $temp : \$temp;
+ # An lvalue ref \substr should be avoided,
+ # since its value is affected by modification of its referent.
+ }
+ else {
+ return;
+ }
+}
+
+##
+## arrayref matching parts = gmatch(string, substring)
+##
+sub gmatch
+{
+ my $self = shift;
+ my $str = shift;
+ my $sub = shift;
+ return map substr($str, $_->[0], $_->[1]),
+ $self->index($str, $sub, 0, 'g');
+}
+
+##
+## bool subst'ed = subst(string, substring, replace)
+##
+sub subst
+{
+ my $self = shift;
+ my $code = ref $_[2] eq 'CODE' ? $_[2] : FALSE;
+
+ if (my($pos,$len) = $self->index($_[0], $_[1])) {
+ if ($code) {
+ my $mat = substr($_[0], $pos, $len);
+ substr($_[0], $pos, $len, $code->($mat));
+ } else {
+ substr($_[0], $pos, $len, $_[2]);
+ }
+ return TRUE;
+ }
+ else {
+ return FALSE;
+ }
+}
+
+##
+## int count = gsubst(string, substring, replace)
+##
+sub gsubst
+{
+ my $self = shift;
+ my $code = ref $_[2] eq 'CODE' ? $_[2] : FALSE;
+ my $cnt = 0;
+
+ # Replacement is carried out from the end, then use reverse.
+ for my $pos_len (reverse $self->index($_[0], $_[1], 0, 'g')) {
+ if ($code) {
+ my $mat = substr($_[0], $pos_len->[0], $pos_len->[1]);
+ substr($_[0], $pos_len->[0], $pos_len->[1], $code->($mat));
+ } else {
+ substr($_[0], $pos_len->[0], $pos_len->[1], $_[2]);
+ }
+ $cnt++;
+ }
+ return $cnt;
+}
+
1;
__END__
#compare
$result = $Collator->cmp($a, $b); # returns 1, 0, or -1.
+ # If %tailoring is false (i.e. empty),
+ # $Collator should do the default collation.
+
=head1 DESCRIPTION
+This module is an implementation of Unicode Technical Standard #10
+(a.k.a. UTS #10) - Unicode Collation Algorithm (a.k.a. UCA).
+
=head2 Constructor and Tailoring
The C<new> method returns a collator object.
$Collator = Unicode::Collate->new(
UCA_Version => $UCA_Version,
- alternate => $alternate,
+ alternate => $alternate, # deprecated: use of 'variable' is recommended.
backwards => $levelNumber, # or \@levelNumbers
entry => $element,
- normalization => $normalization_form,
+ 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,
undefName => qr/$undefName/,
undefChar => qr/$undefChar/,
upper_before_lower => $bool,
+ variable => $variable,
);
- # if %tailoring is false (i.e. empty),
- # $Collator should do the default collation.
=over 4
=item UCA_Version
-If the version number of the older UCA is given,
-the older behavior of that version is emulated on collating.
+If the tracking version number of UCA is given,
+behavior of that tracking version is emulated on collating.
If omitted, the return value of C<UCA_Version()> is used.
+C<UCA_Version()> should return the latest tracking version supported.
-The supported version: 8 or 9.
-
-B<This parameter may be removed in the future version,
-as switching the algorithm would affect the performance.>
-
-=item alternate
-
--- see 3.2.2 Alternate Weighting, UTR #10.
+The supported tracking version: 8, 9, 11, or 14.
-This key allows to alternate weighting for variable collation elements,
-which are marked with an ASTERISK in the table
-(NOTE: Many punction marks and symbols are variable in F<allkeys.txt>).
-
- alternate => 'blanked', 'non-ignorable', 'shifted', or 'shift-trimmed'.
+ UCA Unicode Standard DUCET (@version)
+ ---------------------------------------------------
+ 8 3.1 3.0.1 (3.0.1d9)
+ 9 3.1 with Corrigendum 3 3.1.1 (3.1.1)
+ 11 4.0 4.0.0 (4.0.0)
+ 14 4.1.0 4.1.0 (4.1.0)
-These names are case-insensitive.
-By default (if specification is omitted), 'shifted' is adopted.
+Note: Recent UTS #10 renames "Tracking Version" to "Revision."
- 'Blanked' Variable elements are ignorable at levels 1 through 3;
- considered at the 4th level.
-
- 'Non-ignorable' Variable elements are not reset to ignorable.
+=item alternate
- 'Shifted' Variable elements are 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.
+-- see 3.2.2 Alternate Weighting, version 8 of UTS #10
- 'Shift-Trimmed' Same as 'shifted', but all FFFF's at the 4th level
- are trimmed.
+For backward compatibility, C<alternate> (old name) can be used
+as an alias for C<variable>.
=item backwards
--- see 3.1.2 French Accents, UTR #10.
+-- see 3.1.2 French Accents, UTS #10.
backwards => $levelNumber or \@levelNumbers
=item entry
--- see 3.1 Linguistic Features; 3.2.1 File Format, UTR #10.
+-- 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 C<table>,
+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
+
+B<NOTE:> The code point in the UCA file format (before C<';'>)
+B<must> be a Unicode code point (defined as hexadecimal),
+but not a native code point.
+So C<0063> must always denote C<U+0063>,
+but not a character of C<"\x63">.
+
+Weighting may vary depending on collation element table.
+So ensure the weights defined in C<entry> will be consistent with
+those in the collation element table loaded via C<table>.
+
+In DUCET v4.0.0, primary weight of C<C> is C<0E60>
+and that of C<D> is C<0E6D>. So setting primary weight of C<CH> to C<0E6A>
+(as a value between C<0E60> and C<0E6D>)
+makes ordering as C<C E<lt> CH E<lt> D>.
+Exactly speaking DUCET already has some characters between C<C> and C<D>:
+C<small capital C> (C<U+1D04>) with primary weight C<0E64>,
+C<c-hook/C-hook> (C<U+0188/U+0187>) with C<0E65>,
+and C<c-curl> (C<U+0255>) with C<0E69>.
+Then primary weight C<0E6A> for C<CH> makes C<CH>
+ordered between C<c-curl> and C<D>.
+
+=item 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 C<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 F<the Unicode Standard>
+and F<HangulSyllableType.txt>.
+
+B<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.
-Overrides a default order or defines additional collation elements
-
- entry => <<'ENTRIES', # use the UCA file format
-00E6 ; [.0861.0020.0002.00E6] [.08B1.0020.0002.00E6] # ligature <ae> as <a><e>
-0063 0068 ; [.0893.0020.0002.0063] # "ch" in traditional Spanish
-0043 0068 ; [.0893.0020.0008.0043] # "Ch" in traditional Spanish
-ENTRIES
+=item ignoreChar
=item ignoreName
-=item ignoreChar
+-- see 3.2.2 Variable Weighting, UTS #10.
--- see Completely Ignorable, 3.2.2 Alternate Weighting, UTR #10.
+Makes the entry in the table completely ignorable;
+i.e. as if the weights were zero at all level.
-Makes the entry in the table ignorable.
-If a collation element is ignorable,
-it is ignored as if the element had been deleted from there.
+Through C<ignoreChar>, any character matching C<qr/$ignoreChar/>
+will be ignored. Through C<ignoreName>, any character whose name
+(given in the C<table> file as a comment) matches C<qr/$ignoreName/>
+will be ignored.
E.g. when 'a' and 'e' are ignorable,
'element' is equal to 'lament' (or 'lmnt').
+=item katakana_before_hiragana
+
+-- see 7.3.1 Tertiary Weight Table, UTS #10.
+
+By default, hiragana is before katakana.
+If the parameter is made true, this is reversed.
+
+B<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.
+
=item level
--- see 4.3 Form a sort key for each string, UTR #10.
+-- 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 alternate is 'shifted')
+ Level 4: tie-breaking (e.g. in the case when variable is 'shifted')
ex.level => 2,
=item normalization
--- see 4.1 Normalize each input string, UTR #10.
+-- see 4.1 Normalize, UTS #10.
If specified, strings are normalized before preparation of sort keys
(the normalization is executed after preprocess).
-As a form name, one of the following names must be used.
+A form name C<Unicode::Normalize::normalize()> accepts will be applied
+as C<$normalization_form>.
+Acceptable names include C<'NFD'>, C<'NFC'>, C<'NFKD'>, and C<'NFKC'>.
+See C<Unicode::Normalize::normalize()> for detail.
+If omitted, C<'NFD'> is used.
- 'C' or 'NFC' for Normalization Form C
- 'D' or 'NFD' for Normalization Form D
- 'KC' or 'NFKC' for Normalization Form KC
- 'KD' or 'NFKD' for Normalization Form KD
+C<normalization> is performed after C<preprocess> (if defined).
-If omitted, the string is put into Normalization Form D.
+Furthermore, special values, C<undef> and C<"prenormalized">, can be used,
+though they are not concerned with C<Unicode::Normalize::normalize()>.
-If C<undef> is passed explicitly as the value for this key,
+If C<undef> (not a string C<"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).
-
-see B<CAVEAT>.
+if any normalization is not desired). Under C<(normalization =E<gt> undef)>,
+only contiguous contractions are resolved;
+e.g. even if C<A-ring> (and C<A-ring-cedilla>) is ordered after C<Z>,
+C<A-cedilla-ring> would be primary equal to C<A>.
+In this point,
+C<(normalization =E<gt> undef, preprocess =E<gt> sub { NFD(shift) })>
+B<is not> equivalent to C<(normalization =E<gt> 'NFD')>.
+
+In the case of C<(normalization =E<gt> "prenormalized")>,
+any normalization is not performed, but
+non-contiguous contractions with combining characters are performed.
+Therefore
+C<(normalization =E<gt> 'prenormalized', preprocess =E<gt> sub { NFD(shift) })>
+B<is> equivalent to C<(normalization =E<gt> 'NFD')>.
+If source strings are finely prenormalized,
+C<(normalization =E<gt> 'prenormalized')> may save time for normalization.
+
+Except C<(normalization =E<gt> undef)>,
+B<Unicode::Normalize> is required (see also B<CAVEAT>).
=item overrideCJK
--- see 7.1 Derived Collation Elements, UTR #10.
+-- see 7.1 Derived Collation Elements, UTS #10.
+
+By default, CJK Unified Ideographs are ordered in Unicode codepoint order
+but C<CJK Unified Ideographs> (if C<UCA_Version> is 8 to 11, its range is
+C<U+4E00..U+9FA5>; if C<UCA_Version> is 14, its range is C<U+4E00..U+9FBB>)
+are lesser than C<CJK Unified Ideographs Extension> (its range is
+C<U+3400..U+4DB5> and C<U+20000..U+2A6D6>).
-By default, mapping of CJK Unified Ideographs
-uses the Unicode codepoint order.
-But the mapping of CJK Unified Ideographs may be overrided.
+Through C<overrideCJK>, ordering of CJK Unified Ideographs can be overrided.
ex. CJK Unified Ideographs in the JIS code point order.
If C<undef> 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 L<entry> is still valid.
+in table or C<entry> is still valid.
=item overrideHangul
--- see 7.1 Derived Collation Elements, UTR #10.
+-- see 7.1 Derived Collation Elements, UTS #10.
-By default, Hangul Syllables are decomposed into Hangul Jamo.
+By default, Hangul Syllables are decomposed into Hangul Jamo,
+even if C<(normalization =E<gt> undef)>.
But the mapping of Hangul Syllables may be overrided.
-This tag works like L<overrideCJK>, so see there for examples.
+This parameter works like C<overrideCJK>, so see there for examples.
If you want to override the mapping of Hangul Syllables,
-the Normalization Forms D and KD are not appropriate
-(they will be decomposed before overriding).
+NFD, NFKD, and FCD are not appropriate,
+since they will decompose Hangul Syllables before overriding.
If C<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 L<entry> is still valid.
+in table or C<entry> is still valid.
=item preprocess
--- see 5.1 Preprocessing, UTR #10.
+-- see 5.1 Preprocessing, UTS #10.
If specified, the coderef is used to preprocess
before the formation of sort keys.
preprocess => sub {
my $str = shift;
$str =~ s/\b(?:an?|the)\s+//gi;
- $str;
+ return $str;
},
+C<preprocess> is performed before C<normalization> (if defined).
+
=item rearrange
--- see 3.1.3 Rearrangement, UTR #10.
+-- see 3.1.3 Rearrangement, UTS #10.
Characters that are not coded in logical order and to be rearranged.
-By default,
+If C<UCA_Version> is equal to or lesser than 11, default is:
rearrange => [ 0x0E40..0x0E44, 0x0EC0..0x0EC4 ],
-If you want to disallow any rearrangement,
-pass C<undef> or C<[]> (a reference to an empty list)
-as the value for this key.
+If you want to disallow any rearrangement, pass C<undef> or C<[]>
+(a reference to empty list) as the value for this key.
+
+If C<UCA_Version> is equal to 14, default is C<[]> (i.e. no rearrangement).
B<According to the version 9 of UCA, this parameter shall not be used;
but it is not warned at present.>
=item table
--- see 3.2 Default Unicode Collation Element Table, UTR #10.
+-- see 3.2 Default Unicode Collation Element Table, UTS #10.
+
+You can use another collation element table if desired.
-You can use another element table if desired.
-The table file must be in your C<lib/Unicode/Collate> directory.
+The table file should locate in the F<Unicode/Collate> directory
+on C<@INC>. Say, if the filename is F<Foo.txt>,
+the table file is searched as F<Unicode/Collate/Foo.txt> in C<@INC>.
-By default, the file C<lib/Unicode/Collate/allkeys.txt> is used.
+By default, F<allkeys.txt> (as the filename of DUCET) is used.
+If you will prepare your own table file, any name other than F<allkeys.txt>
+may be better to avoid namespace conflict.
If C<undef> is passed explicitly as the value for this key,
-no file is read (but you can define collation elements via L<entry>).
+no file is read (but you can define collation elements via C<entry>).
A typical way to define a collation element table
without any file of table:
ENTRIES
);
-=item undefName
+If C<ignoreName> or C<undefName> is used, character names should be
+specified as a comment (following C<#>) on each line.
=item undefChar
--- see 6.3.4 Reducing the Repertoire, UTR #10.
+=item undefName
+
+-- 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.
But, it'd be better to ignore characters
unfamiliar to you and maybe never used.
-=item katakana_before_hiragana
+Through C<undefChar>, any character matching C<qr/$undefChar/>
+will be undefined. Through C<undefName>, any character whose name
+(given in the C<table> file as a comment) matches C<qr/$undefName/>
+will be undefined.
+
+ex. Collation weights for beyond-BMP characters are not stored in object:
+
+ undefChar => qr/[^\0-\x{fffd}]/,
=item upper_before_lower
--- see 6.6 Case Comparisons; 7.3.1 Tertiary Weight Table, UTR #10.
+-- see 6.6 Case Comparisons, UTS #10.
+
+By default, lowercase is before uppercase.
+If the parameter is made true, this is reversed.
+
+B<NOTE>: This parameter simplemindedly assumes that any lowercase/uppercase
+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 differs from this requirement,
+this parameter doesn't work validly.
+
+=item variable
+
+-- see 3.2.2 Variable Weighting, UTS #10.
+
+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 F<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.
-By default, lowercase is before uppercase
-and hiragana is before katakana.
+ 'Non-Ignorable' Variable elements are not reset to ignorable.
-If the tag is made true, this is reversed.
+ '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.
-B<NOTE>: These tags simplemindedly assume
-any lowercase/uppercase or hiragana/katakana distinctions
-should occur in level 3, and their weights at level 3
-should be same as those mentioned in 7.3.1, UTR #10.
-If you define your collation elements which violates this,
-these tags doesn't work validly.
+ 'Shift-Trimmed' Same as 'shifted', but all FFFF's at the 4th level
+ are trimmed.
=back
=item C<$sortKey = $Collator-E<gt>getSortKey($string)>
--- see 4.3 Form a sort key for each string, UTR #10.
+-- see 4.3 Form Sort Key, UTS #10.
Returns a sort key.
=item C<$sortKeyForm = $Collator-E<gt>viewSortKey($string)>
+Converts a sorting key into its representation form.
+If C<UCA_Version> is 8, the output is slightly different.
+
use Unicode::Collate;
my $c = Unicode::Collate->new();
print $c->viewSortKey("Perl"),"\n";
# [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.)
+=back
+
+=head2 Methods for Searching
-=item C<$position = $Collator-E<gt>index($string, $substring)>
+B<DISCLAIMER:> If C<preprocess> or C<normalization> parameter is true
+for C<$Collator>, calling these methods (C<index>, C<match>, C<gmatch>,
+C<subst>, C<gsubst>) is croaked,
+as the position and the length might differ
+from those on the specified string.
+(And C<rearrange> and C<hangul_terminator> parameters are neglected.)
-=item C<($position, $length) = $Collator-E<gt>index($string, $substring)>
+The C<match>, C<gmatch>, C<subst>, C<gsubst> methods work
+like C<m//>, C<m//g>, C<s///>, C<s///g>, respectively,
+but they are not aware of any pattern, but only a literal substring.
--- see 6.8 Searching, UTR #10.
+=over 4
+
+=item C<$position = $Collator-E<gt>index($string, $substring[, $position])>
+
+=item C<($position, $length) = $Collator-E<gt>index($string, $substring[, $position])>
If C<$substring> matches a part of C<$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.
-B<Notice> that the length of the matching part may differ from
-the length of C<$substring>.
-
-B<Note> that the position and the length are counted on the string
-after the process of preprocess, normalization, and rearrangement.
-Therefore, in case the specified string is not binary equal to
-the preprocessed/normalized/rearranged string, the position and the length
-may differ form those on the specified string. But it is guaranteed
-that, if matched, it returns a non-negative value as C<$position>.
-
If C<$substring> does not match any part of C<$string>,
returns C<-1> in scalar context and
an empty list in list context.
e.g. you say
my $Collator = Unicode::Collate->new( normalization => undef, level => 1 );
- my $str = "Ich mu\x{00DF} studieren.";
- my $sub = "m\x{00FC}ss";
+ # (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 C<"mu\x{00DF}"> in C<$match> since C<"mu>E<223>C<">
-is primary equal to C<"m>E<252>C<ss">.
+and get C<"muß"> in C<$match> since C<"muß">
+is primary equal to C<"MÜSS">.
+
+=item C<$match_ref = $Collator-E<gt>match($string, $substring)>
+
+=item C<($match) = $Collator-E<gt>match($string, $substring)>
+
+If C<$substring> matches a part of C<$string>, in scalar context, returns
+B<a reference to> the first occurrence of the matching part
+(C<$match_ref> is always true if matches,
+since every reference is B<true>);
+in list context, returns the first occurrence of the matching part.
+
+If C<$substring> does not match any part of C<$string>,
+returns C<undef> 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";
+ }
+
+=item C<@match = $Collator-E<gt>gmatch($string, $substring)>
+
+If C<$substring> matches a part of C<$string>, returns
+all the matching parts (or matching count in scalar context).
+
+If C<$substring> does not match any part of C<$string>,
+returns an empty list.
+
+=item C<$count = $Collator-E<gt>subst($string, $substring, $replacement)>
+
+If C<$substring> matches a part of C<$string>,
+the first occurrence of the matching part is replaced by C<$replacement>
+(C<$string> is modified) and return C<$count> (always equals to C<1>).
+
+C<$replacement> can be a C<CODEREF>,
+taking the matching part as an argument,
+and returning a string to replace the matching part
+(a bit similar to C<s/(..)/$coderef-E<gt>($1)/e>).
+
+=item C<$count = $Collator-E<gt>gsubst($string, $substring, $replacement)>
+
+If C<$substring> matches a part of C<$string>,
+all the occurrences of the matching part is replaced by C<$replacement>
+(C<$string> is modified) and return C<$count>.
+
+C<$replacement> can be a C<CODEREF>,
+taking the matching part as an argument,
+and returning a string to replace the matching part
+(a bit similar to C<s/(..)/$coderef-E<gt>($1)/eg>).
+
+e.g.
+
+ my $Collator = Unicode::Collate->new( normalization => undef, level => 1 );
+ # (normalization => undef) is REQUIRED.
+ my $str = "Camel donkey zebra came\x{301}l CAMEL horse cAm\0E\0L...";
+ $Collator->gsubst($str, "camel", sub { "<b>$_[0]</b>" });
+
+ # now $str is "<b>Camel</b> donkey zebra <b>came\x{301}l</b> <b>CAMEL</b> horse <b>cAm\0E\0L</b>...";
+ # i.e., all the camels are made bold-faced.
=back
$Collator->change(level => 4)->eq("perl", "PERL"); # false
-=item UCA_Version
+=item C<$version = $Collator-E<gt>version()>
+
+Returns the version number (a string) of the Unicode Standard
+which the C<table> file used by the collator object is based on.
+If the table does not include a version line (starting with C<@version>),
+returns C<"unknown">.
+
+=item C<UCA_Version()>
-Returns the version number of Unicode Technical Standard 10
-this module consults.
+Returns the tracking version number of UTS #10 this module consults.
-=item Base_Unicode_Version
+=item C<Base_Unicode_Version()>
-Returns the version number of the Unicode Standard
-this module is based on.
+Returns the version number of UTS #10 this module consults.
=back
-=head2 EXPORT
+=head1 EXPORT
-None by default.
+No method will be exported.
-=head2 TODO
+=head1 INSTALL
-Unicode::Collate has not been ported to EBCDIC. The code mostly would
-work just fine but a decision needs to be made: how the module should
-work in EBCDIC? Should the low 256 characters be understood as
-Unicode or as EBCDIC code points? Should one be chosen or should
-there be a way to do either? Or should such translation be left
-outside the module for the user to do, for example by using
-Encode::from_to()?
-(or utf8::unicode_to_native()/utf8::native_to_unicode()?)
+Though this module can be used without any C<table> file,
+to use this module easily, it is recommended to install a table file
+in the UCA format, by copying it under the directory
+<a place in @INC>/Unicode/Collate.
-=head2 CAVEAT
+The most preferable one is "The Default Unicode Collation Element Table"
+(aka DUCET), available from the Unicode Consortium's website:
-Use of the C<normalization> parameter requires
-the B<Unicode::Normalize> module.
+ http://www.unicode.org/Public/UCA/
+
+ http://www.unicode.org/Public/UCA/latest/allkeys.txt (latest version)
+
+If DUCET is not installed, it is recommended to copy the file
+from http://www.unicode.org/Public/UCA/latest/allkeys.txt
+to <a place in @INC>/Unicode/Collate/allkeys.txt
+manually.
+
+=head1 CAVEATS
+
+=over 4
+
+=item Normalization
+
+Use of the C<normalization> parameter requires the B<Unicode::Normalize>
+module (see L<Unicode::Normalize>).
If you need not it (say, in the case when you need not
handle any combining characters),
assign C<normalization =E<gt> undef> explicitly.
--- see 6.5 Avoiding Normalization, UTR #10.
+-- see 6.5 Avoiding Normalization, UTS #10.
-=head2 Conformance Test
+=item Conformance Test
-The Conformance Test for the UCA is provided
-in L<http://www.unicode.org/reports/tr10/CollationTest.html>
-and L<http://www.unicode.org/reports/tr10/CollationTest.zip>
+The Conformance Test for the UCA is available
+under L<http://www.unicode.org/Public/UCA/>.
For F<CollationTest_SHIFTED.txt>,
a collator via C<Unicode::Collate-E<gt>new( )> should be used;
for F<CollationTest_NON_IGNORABLE.txt>, a collator via
-C<Unicode::Collate-E<gt>new(alternate =E<gt> "non-ignorable", level =E<gt> 3)>.
-
-B<Unicode::Normalize is required to try this test.>
-
-=head2 BUGS
+C<Unicode::Collate-E<gt>new(variable =E<gt> "non-ignorable", level =E<gt> 3)>.
-C<index()> is an experimental method and
-its return value may be unreliable.
-The correct implementation for C<index()> must be based
-on Locale-Sensitive Support: Level 3 in UTR #18,
-F<Unicode Regular Expression Guidelines>.
+B<Unicode::Normalize is required to try The Conformance Test.>
-See also 4.2 Locale-Dependent Graphemes in UTR #18.
-
-=head1 AUTHOR
+=back
-SADAHIRO Tomoyuki, E<lt>SADAHIRO@cpan.orgE<gt>
+=head1 AUTHOR, COPYRIGHT AND LICENSE
- http://homepage1.nifty.com/nomenclator/perl/
+The Unicode::Collate module for perl was written by SADAHIRO Tomoyuki,
+<SADAHIRO@cpan.org>. This module is Copyright(C) 2001-2005,
+SADAHIRO Tomoyuki. Japan. All rights reserved.
- Copyright(C) 2001-2002, SADAHIRO Tomoyuki. Japan. All rights reserved.
+This module is free software; you can redistribute it and/or
+modify it under the same terms as Perl itself.
- This library is free software; you can redistribute it
- and/or modify it under the same terms as Perl itself.
+The file Unicode/Collate/allkeys.txt was copied directly
+from L<http://www.unicode.org/Public/UCA/4.1.0/allkeys.txt>.
+This file is Copyright (c) 1991-2005 Unicode, Inc. All rights reserved.
+Distributed under the Terms of Use in L<http://www.unicode.org/copyright.html>.
=head1 SEE ALSO
=over 4
-=item http://www.unicode.org/reports/tr10/
+=item Unicode Collation Algorithm - UTS #10
-Unicode Collation Algorithm - UTR #10
+L<http://www.unicode.org/reports/tr10/>
-=item http://www.unicode.org/reports/tr10/allkeys.txt
+=item The Default Unicode Collation Element Table (DUCET)
-The Default Unicode Collation Element Table
+L<http://www.unicode.org/Public/UCA/latest/allkeys.txt>
-=item http://www.unicode.org/reports/tr10/CollationTest.html
-http://www.unicode.org/reports/tr10/CollationTest.zip
+=item The conformance test for the UCA
-The latest versions of the conformance test for the UCA
+L<http://www.unicode.org/Public/UCA/latest/CollationTest.html>
-=item http://www.unicode.org/reports/tr15/
+L<http://www.unicode.org/Public/UCA/latest/CollationTest.zip>
-Unicode Normalization Forms - UAX #15
+=item Hangul Syllable Type
-=item http://www.unicode.org/reports/tr18
+L<http://www.unicode.org/Public/UNIDATA/HangulSyllableType.txt>
-Unicode Regular Expression Guidelines - UTR #18
+=item Unicode Normalization Forms - UAX #15
-=item L<Unicode::Normalize>
+L<http://www.unicode.org/reports/tr15/>
=back