<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">package Unicode::Collate;

use 5.006;
use strict;
use warnings;
use Carp;
use File::Spec;

no warnings 'utf8';

our $VERSION = '1.31';
our $PACKAGE = __PACKAGE__;

### begin XS only ###
use XSLoader ();
XSLoader::load('Unicode::Collate', $VERSION);
### end XS only ###

my @Path = qw(Unicode Collate);
my $KeyFile = 'allkeys.txt';

# Perl's boolean
use constant TRUE  =&gt; 1;
use constant FALSE =&gt; "";
use constant NOMATCHPOS =&gt; -1;

# A coderef to get combining class imported from Unicode::Normalize
# (i.e. \&amp;Unicode::Normalize::getCombinClass).
# This is also used as a HAS_UNICODE_NORMALIZE flag.
my $CVgetCombinClass;

# Supported Levels
use constant MinLevel =&gt; 1;
use constant MaxLevel =&gt; 4;

# Minimum weights at level 2 and 3, respectively
use constant Min2Wt =&gt; 0x20;
use constant Min3Wt =&gt; 0x02;

# Shifted weight at 4th level
use constant Shift4Wt =&gt; 0xFFFF;

# A boolean for Variable and 16-bit weights at 4 levels of Collation Element
use constant VCE_TEMPLATE =&gt; 'Cn4';

# A sort key: 16-bit weights
use constant KEY_TEMPLATE =&gt; 'n*';

# The tie-breaking: 32-bit weights
use constant TIE_TEMPLATE =&gt; 'N*';

# Level separator in a sort key:
# i.e. pack(KEY_TEMPLATE, 0)
use constant LEVEL_SEP =&gt; "\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 =&gt; ';';
	# NOTE: in regex /;/ is used for $jcps!

# boolean values of variable weights
use constant NON_VAR =&gt; 0; # Non-Variable character
use constant VAR     =&gt; 1; # Variable character

# specific code points
use constant Hangul_SIni   =&gt; 0xAC00;
use constant Hangul_SFin   =&gt; 0xD7A3;

# Logical_Order_Exception in PropList.txt
my $DefaultRearrange = [ 0x0E40..0x0E44, 0x0EC0..0x0EC4 ];

# for highestFFFF and minimalFFFE
my $HighestVCE = pack(VCE_TEMPLATE, 0, 0xFFFE, 0x20, 0x5, 0xFFFF);
my $minimalVCE = pack(VCE_TEMPLATE, 0,      1, 0x20, 0x5, 0xFFFE);

sub UCA_Version { '43' }

sub Base_Unicode_Version { '13.0.0' }

######

my $native_to_unicode = ($::IS_ASCII || $] &lt; 5.008)
	? sub { return shift }
	: sub { utf8::native_to_unicode(shift) };

my $unicode_to_native = ($::IS_ASCII || $] &lt; 5.008)
	? sub { return shift }
	: sub { utf8::unicode_to_native(shift) };

# pack_U() should get Unicode code points.
sub pack_U {
    return pack('U*', map $unicode_to_native-&gt;($_), @_);
}

# unpack_U() should return Unicode code points.
sub unpack_U {
    return map $native_to_unicode-&gt;($_), unpack('U*', shift(@_).pack('U*'));
}
# for older perl version, pack('U*') generates empty string with utf8 flag.

######

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 ignore_level2
    overrideCJK overrideHangul overrideOut preprocess UCA_Version
    hangul_terminator variable identical highestFFFF minimalFFFE
    long_contraction
  /;

our @ChangeNG = qw/
    entry mapping table maxlength contraction
    ignoreChar ignoreName undefChar undefName rewrite
    versionTable alternateTable backwardsTable forwardsTable
    rearrangeTable variableTable
    derivCode normCode rearrangeHash backwardsFlag
    suppress suppressHash
    __useXS /; ### XS only
# The hash key 'ignored' was deleted at v 0.21.
# The hash key 'isShift' was deleted at v 0.23.
# The hash key 'combining' was deleted at v 0.24.
# The hash key 'entries' was deleted at v 0.30.
# The hash key 'L3_ignorable' was deleted at v 0.40.

sub version {
    my $self = shift;
    return $self-&gt;{versionTable} || 'unknown';
}

my (%ChangeOK, %ChangeNG);
@ChangeOK{ @ChangeOK } = ();
@ChangeNG{ @ChangeNG } = ();

sub change {
    my $self = shift;
    my %hash = @_;
    my %old;
    if (exists $hash{alternate}) {
	if (exists $hash{variable}) {
	    delete $hash{alternate};
	} else {
	    $hash{variable} = $hash{alternate};
	}
    }
    foreach my $k (keys %hash) {
	if (exists $ChangeOK{$k}) {
	    $old{$k} = $self-&gt;{$k};
	    $self-&gt;{$k} = $hash{$k};
	} elsif (exists $ChangeNG{$k}) {
	    croak "change of $k via change() is not allowed!";
	}
	# else =&gt; ignored
    }
    $self-&gt;checkCollator();
    return wantarray ? %old : $self;
}

sub _checkLevel {
    my $level = shift;
    my $key   = shift; # 'level' or 'backwards'
    MinLevel &lt;= $level or croak sprintf
	"Illegal level %d (in value for key '%s') lower than %d.",
	    $level, $key, MinLevel;
    $level &lt;= MaxLevel or croak sprintf
	"Unsupported level %d (in value for key '%s') higher than %d.",
	    $level, $key, MaxLevel;
}

my %DerivCode = (
    8 =&gt; \&amp;_derivCE_8,
    9 =&gt; \&amp;_derivCE_9,
   11 =&gt; \&amp;_derivCE_9, # 11 == 9
   14 =&gt; \&amp;_derivCE_14,
   16 =&gt; \&amp;_derivCE_14, # 16 == 14
   18 =&gt; \&amp;_derivCE_18,
   20 =&gt; \&amp;_derivCE_20,
   22 =&gt; \&amp;_derivCE_22,
   24 =&gt; \&amp;_derivCE_24,
   26 =&gt; \&amp;_derivCE_24, # 26 == 24
   28 =&gt; \&amp;_derivCE_24, # 28 == 24
   30 =&gt; \&amp;_derivCE_24, # 30 == 24
   32 =&gt; \&amp;_derivCE_32,
   34 =&gt; \&amp;_derivCE_34,
   36 =&gt; \&amp;_derivCE_36,
   38 =&gt; \&amp;_derivCE_38,
   40 =&gt; \&amp;_derivCE_40,
   41 =&gt; \&amp;_derivCE_40, # 41 == 40
   43 =&gt; \&amp;_derivCE_43,
);

sub checkCollator {
    my $self = shift;
    _checkLevel($self-&gt;{level}, 'level');

    $self-&gt;{derivCode} = $DerivCode{ $self-&gt;{UCA_Version} }
	or croak "Illegal UCA version (passed $self-&gt;{UCA_Version}).";

    $self-&gt;{variable} ||= $self-&gt;{alternate} || $self-&gt;{variableTable} ||
				$self-&gt;{alternateTable} || 'shifted';
    $self-&gt;{variable} = $self-&gt;{alternate} = lc($self-&gt;{variable});
    exists $VariableOK{ $self-&gt;{variable} }
	or croak "$PACKAGE unknown variable parameter name: $self-&gt;{variable}";

    if (! defined $self-&gt;{backwards}) {
	$self-&gt;{backwardsFlag} = 0;
    } elsif (! ref $self-&gt;{backwards}) {
	_checkLevel($self-&gt;{backwards}, 'backwards');
	$self-&gt;{backwardsFlag} = 1 &lt;&lt; $self-&gt;{backwards};
    } else {
	my %level;
	$self-&gt;{backwardsFlag} = 0;
	for my $b (@{ $self-&gt;{backwards} }) {
	    _checkLevel($b, 'backwards');
	    $level{$b} = 1;
	}
	for my $v (sort keys %level) {
	    $self-&gt;{backwardsFlag} += 1 &lt;&lt; $v;
	}
    }

    defined $self-&gt;{rearrange} or $self-&gt;{rearrange} = [];
    ref $self-&gt;{rearrange}
	or croak "$PACKAGE: list for rearrangement must be store in ARRAYREF";

    # keys of $self-&gt;{rearrangeHash} are $self-&gt;{rearrange}.
    $self-&gt;{rearrangeHash} = undef;

    if (@{ $self-&gt;{rearrange} }) {
	@{ $self-&gt;{rearrangeHash} }{ @{ $self-&gt;{rearrange} } } = ();
    }

    $self-&gt;{normCode} = undef;

    if (defined $self-&gt;{normalization}) {
	eval { require Unicode::Normalize };
	$@ and croak "Unicode::Normalize is required to normalize strings";

	$CVgetCombinClass ||= \&amp;Unicode::Normalize::getCombinClass;

	if ($self-&gt;{normalization} =~ /^(?:NF)D\z/) { # tweak for default
	    $self-&gt;{normCode} = \&amp;Unicode::Normalize::NFD;
	}
	elsif ($self-&gt;{normalization} ne 'prenormalized') {
	    my $norm = $self-&gt;{normalization};
	    $self-&gt;{normCode} = sub {
		Unicode::Normalize::normalize($norm, shift);
	    };
	    eval { $self-&gt;{normCode}-&gt;("") }; # try
	    $@ and croak "$PACKAGE unknown normalization form name: $norm";
	}
    }
    return;
}

sub new
{
    my $class = shift;
    my $self = bless { @_ }, $class;

### begin XS only ###
    if (! exists $self-&gt;{table}     &amp;&amp; !defined $self-&gt;{rewrite} &amp;&amp;
	!defined $self-&gt;{undefName} &amp;&amp; !defined $self-&gt;{ignoreName} &amp;&amp;
	!defined $self-&gt;{undefChar} &amp;&amp; !defined $self-&gt;{ignoreChar}) {
	$self-&gt;{__useXS} = \&amp;_fetch_simple;
    } else {
	$self-&gt;{__useXS} = undef;
    }
### end XS only ###

    # keys of $self-&gt;{suppressHash} are $self-&gt;{suppress}.
    if ($self-&gt;{suppress} &amp;&amp; @{ $self-&gt;{suppress} }) {
	@{ $self-&gt;{suppressHash} }{ @{ $self-&gt;{suppress} } } = ();
    } # before read_table()

    # If undef is passed explicitly, no file is read.
    $self-&gt;{table} = $KeyFile if ! exists $self-&gt;{table};
    $self-&gt;read_table() if defined $self-&gt;{table};

    if ($self-&gt;{entry}) {
	while ($self-&gt;{entry} =~ /([^\n]+)/g) {
	    $self-&gt;parseEntry($1, TRUE);
	}
    }

    # only in new(), not in change()
    $self-&gt;{level} ||= MaxLevel;
    $self-&gt;{UCA_Version} ||= UCA_Version();

    $self-&gt;{overrideHangul} = FALSE
	if ! exists $self-&gt;{overrideHangul};
    $self-&gt;{overrideCJK} = FALSE
	if ! exists $self-&gt;{overrideCJK};
    $self-&gt;{normalization} = 'NFD'
	if ! exists $self-&gt;{normalization};
    $self-&gt;{rearrange} = $self-&gt;{rearrangeTable} ||
	($self-&gt;{UCA_Version} &lt;= 11 ? $DefaultRearrange : [])
	if ! exists $self-&gt;{rearrange};
    $self-&gt;{backwards} = $self-&gt;{backwardsTable}
	if ! exists $self-&gt;{backwards};
    exists $self-&gt;{long_contraction} or $self-&gt;{long_contraction}
	= 22 &lt;= $self-&gt;{UCA_Version} &amp;&amp; $self-&gt;{UCA_Version} &lt;= 24;

    # checkCollator() will be called in change()
    $self-&gt;checkCollator();

    return $self;
}

sub parseAtmark {
    my $self = shift;
    my $line = shift; # after s/^\s*\@//

    if ($line =~ /^version\s*(\S*)/) {
	$self-&gt;{versionTable} ||= $1;
    }
    elsif ($line =~ /^variable\s+(\S*)/) { # since UTS #10-9
	$self-&gt;{variableTable} ||= $1;
    }
    elsif ($line =~ /^alternate\s+(\S*)/) { # till UTS #10-8
	$self-&gt;{alternateTable} ||= $1;
    }
    elsif ($line =~ /^backwards\s+(\S*)/) {
	push @{ $self-&gt;{backwardsTable} }, $1;
    }
    elsif ($line =~ /^forwards\s+(\S*)/) { # perhaps no use
	push @{ $self-&gt;{forwardsTable} }, $1;
    }
    elsif ($line =~ /^rearrange\s+(.*)/) { # (\S*) is NG
	push @{ $self-&gt;{rearrangeTable} }, _getHexArray($1);
    }
}

sub read_table {
    my $self = shift;

### begin XS only ###
    if ($self-&gt;{__useXS}) {
	my @rest = _fetch_rest(); # complex matter need to parse
	for my $line (@rest) {
	    next if $line =~ /^\s*#/;

	    if ($line =~ s/^\s*\@//) {
		$self-&gt;parseAtmark($line);
	    } else {
		$self-&gt;parseEntry($line);
	    }
	}
	return;
    }
### end XS only ###

    my($f, $fh);
    foreach my $d (@INC) {
	$f = File::Spec-&gt;catfile($d, @Path, $self-&gt;{table});
	last if open($fh, $f);
	$f = undef;
    }
    if (!defined $f) {
	$f = File::Spec-&gt;catfile(@Path, $self-&gt;{table});
	croak("$PACKAGE: Can't locate $f in \@INC (\@INC contains: @INC)");
    }

    while (my $line = &lt;$fh&gt;) {
	next if $line =~ /^\s*#/;

	if ($line =~ s/^\s*\@//) {
	    $self-&gt;parseAtmark($line);
	} else {
	    $self-&gt;parseEntry($line);
	}
    }
    close $fh;
}


##
## get $line, parse it, and write an entry in $self
##
sub parseEntry
{
    my $self = shift;
    my $line = shift;
    my $tailoring = shift;
    my($name, $entry, @uv, @key);

    if (defined $self-&gt;{rewrite}) {
	$line = $self-&gt;{rewrite}-&gt;($line);
    }

    return if $line !~ /^\s*[0-9A-Fa-f]/;

    # removes comment and gets name
    $name = $1
	if $line =~ s/[#%]\s*(.*)//;
    return if defined $self-&gt;{undefName} &amp;&amp; $name =~ /$self-&gt;{undefName}/;

    # gets element
    my($e, $k) = split /;/, $line;
    croak "Wrong Entry: &lt;charList&gt; must be separated by ';' from &lt;collElement&gt;"
	if ! $k;

    @uv = _getHexArray($e);
    return if !@uv;
    return if @uv &gt; 1 &amp;&amp; $self-&gt;{suppressHash} &amp;&amp; !$tailoring &amp;&amp;
		  exists $self-&gt;{suppressHash}{$uv[0]};
    $entry = join(CODE_SEP, @uv); # in JCPS

    if (defined $self-&gt;{undefChar} || defined $self-&gt;{ignoreChar}) {
	my $ele = pack_U(@uv);

	# regarded as if it were not stored in the table
	return
	    if defined $self-&gt;{undefChar} &amp;&amp; $ele =~ /$self-&gt;{undefChar}/;

	# replaced as completely ignorable
	$k = '[.0000.0000.0000.0000]'
	    if defined $self-&gt;{ignoreChar} &amp;&amp; $ele =~ /$self-&gt;{ignoreChar}/;
    }

    # replaced as completely ignorable
    $k = '[.0000.0000.0000.0000]'
	if defined $self-&gt;{ignoreName} &amp;&amp; $name =~ /$self-&gt;{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].
    }

    # mapping: be an array ref or not exists (any false value is disallowed)
    $self-&gt;{mapping}{$entry} = $is_L3_ignorable ? [] : \@key;

    # maxlength: be more than 1 or not exists (any false value is disallowed)
    if (@uv &gt; 1) {
	if (!$self-&gt;{maxlength}{$uv[0]} || $self-&gt;{maxlength}{$uv[0]} &lt; @uv) {
	    $self-&gt;{maxlength}{$uv[0]} = @uv;
	}
    }

    # contraction: be 1 or not exists (any false value is disallowed)
    while (@uv &gt; 2) {
	pop @uv;
	my $fake_entry = join(CODE_SEP, @uv); # in JCPS
	$self-&gt;{contraction}{$fake_entry} = 1;
    }
}


sub viewSortKey
{
    my $self = shift;
    my $str  = shift;
    $self-&gt;visualizeSortKey($self-&gt;getSortKey($str));
}


sub process
{
    my $self = shift;
    my $str  = shift;
    my $prep = $self-&gt;{preprocess};
    my $norm = $self-&gt;{normCode};

    $str = &amp;$prep($str) if ref $prep;
    $str = &amp;$norm($str) if ref $norm;
    return $str;
}

##
## arrayref of JCPS   = splitEnt(string to be collated)
## arrayref of arrayref[JCPS, ini_pos, fin_pos] = splitEnt(string, TRUE)
##
sub splitEnt
{
    my $self = shift;
    my $str  = shift;
    my $wLen = shift; # with Length

    my $map  = $self-&gt;{mapping};
    my $max  = $self-&gt;{maxlength};
    my $reH  = $self-&gt;{rearrangeHash};
    my $vers = $self-&gt;{UCA_Version};
    my $ver9 = $vers &gt;= 9 &amp;&amp; $vers &lt;= 11;
    my $long = $self-&gt;{long_contraction};
    my $uXS  = $self-&gt;{__useXS}; ### XS only

    my @buf;

    # get array of Unicode code point of string.
    my @src = unpack_U($str);

    # rearrangement:
    # Character positions are not kept if rearranged,
    # then neglected if $wLen is true.
    if ($reH &amp;&amp; ! $wLen) {
	for (my $i = 0; $i &lt; @src; $i++) {
	    if (exists $reH-&gt;{ $src[$i] } &amp;&amp; $i + 1 &lt; @src) {
		($src[$i], $src[$i+1]) = ($src[$i+1], $src[$i]);
		$i++;
	    }
	}
    }

    # remove a code point marked as a completely ignorable.
    for (my $i = 0; $i &lt; @src; $i++) {
	if ($vers &lt;= 20 &amp;&amp; _isIllegal($src[$i])) {
	    $src[$i] = undef;
	} elsif ($ver9) {
	    $src[$i] = undef if exists $map-&gt;{ $src[$i] }
			   ? @{ $map-&gt;{ $src[$i] } } == 0
			   : $uXS &amp;&amp; _ignorable_simple($src[$i]); ### XS only
	}
    }

    for (my $i = 0; $i &lt; @src; $i++) {
	my $jcps = $src[$i];

	# skip removed code point
	if (! defined $jcps) {
	    if ($wLen &amp;&amp; @buf) {
		$buf[-1][2] = $i + 1;
	    }
	    next;
	}

	my $i_orig = $i;

	# find contraction
	if (exists $max-&gt;{$jcps}) {
	    my $temp_jcps = $jcps;
	    my $jcpsLen = 1;
	    my $maxLen = $max-&gt;{$jcps};

	    for (my $p = $i + 1; $jcpsLen &lt; $maxLen &amp;&amp; $p &lt; @src; $p++) {
		next if ! defined $src[$p];
		$temp_jcps .= CODE_SEP . $src[$p];
		$jcpsLen++;
		if (exists $map-&gt;{$temp_jcps}) {
		    $jcps = $temp_jcps;
		    $i = $p;
		}
	    }

	# discontiguous 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.

	    # $self-&gt;{normCode} is false in the case of "prenormalized".
	    if ($self-&gt;{normalization}) {
		my $cont = $self-&gt;{contraction};
		my $preCC = 0;
		my $preCC_uc = 0;
		my $jcps_uc = $jcps;
		my(@out, @out_uc);

		for (my $p = $i + 1; $p &lt; @src; $p++) {
		    next if ! defined $src[$p];
		    my $curCC = $CVgetCombinClass-&gt;($src[$p]);
		    last unless $curCC;
		    my $tail = CODE_SEP . $src[$p];

		    if ($preCC != $curCC &amp;&amp; exists $map-&gt;{$jcps.$tail}) {
			$jcps .= $tail;
			push @out, $p;
		    } else {
			$preCC = $curCC;
		    }

		    next if !$long;

		    if ($preCC_uc != $curCC &amp;&amp;
			    (exists $map-&gt;{$jcps_uc.$tail} ||
			    exists $cont-&gt;{$jcps_uc.$tail})) {
			$jcps_uc .= $tail;
			push @out_uc, $p;
		    } else {
			$preCC_uc = $curCC;
		    }
		}

		if (@out_uc &amp;&amp; exists $map-&gt;{$jcps_uc}) {
		    $jcps = $jcps_uc;
		    $src[$_] = undef for @out_uc;
		} else {
		    $src[$_] = undef for @out;
		}
	    }
	}

	# skip completely ignorable
	if (exists $map-&gt;{$jcps} ? @{ $map-&gt;{$jcps} } == 0 :
	    $uXS &amp;&amp; $jcps !~ /;/ &amp;&amp; _ignorable_simple($jcps)) { ### XS only
	    if ($wLen &amp;&amp; @buf) {
		$buf[-1][2] = $i + 1;
	    }
	    next;
	}

	push @buf, $wLen ? [$jcps, $i_orig, $i + 1] : $jcps;
    }
    return \@buf;
}

##
## VCE = _pack_override(input, codepoint, derivCode)
##
sub _pack_override ($$$) {
    my $r = shift;
    my $u = shift;
    my $der = shift;

    if (ref $r) {
	return pack(VCE_TEMPLATE, NON_VAR, @$r);
    } elsif (defined $r) {
	return pack(VCE_TEMPLATE, NON_VAR, $r, Min2Wt, Min3Wt, $u);
    } else {
	$u = 0xFFFD if 0x10FFFF &lt; $u;
	return $der-&gt;($u);
    }
}

##
## list of VCE = getWt(JCPS)
##
sub getWt
{
    my $self = shift;
    my $u    = shift;
    my $map  = $self-&gt;{mapping};
    my $der  = $self-&gt;{derivCode};
    my $out  = $self-&gt;{overrideOut};
    my $uXS  = $self-&gt;{__useXS}; ### XS only

    return if !defined $u;
    return $self-&gt;varCE($HighestVCE) if $u eq 0xFFFF &amp;&amp; $self-&gt;{highestFFFF};
    return $self-&gt;varCE($minimalVCE) if $u eq 0xFFFE &amp;&amp; $self-&gt;{minimalFFFE};
    $u = 0xFFFD if $u !~ /;/ &amp;&amp; 0x10FFFF &lt; $u &amp;&amp; !$out;

    my @ce;
    if (exists $map-&gt;{$u}) {
	@ce = @{ $map-&gt;{$u} }; # $u may be a contraction
### begin XS only ###
    } elsif ($uXS &amp;&amp; _exists_simple($u)) {
	@ce = _fetch_simple($u);
### end XS only ###
    } elsif (Hangul_SIni &lt;= $u &amp;&amp; $u &lt;= Hangul_SFin) {
	my $hang = $self-&gt;{overrideHangul};
	if ($hang) {
	    @ce = map _pack_override($_, $u, $der), $hang-&gt;($u);
	} elsif (!defined $hang) {
	    @ce = $der-&gt;($u);
	} else {
	    my $max  = $self-&gt;{maxlength};
	    my @decH = _decompHangul($u);

	    if (@decH == 2) {
		my $contract = join(CODE_SEP, @decH);
		@decH = ($contract) if exists $map-&gt;{$contract};
	    } else { # must be &lt;@decH == 3&gt;
		if (exists $max-&gt;{$decH[0]}) {
		    my $contract = join(CODE_SEP, @decH);
		    if (exists $map-&gt;{$contract}) {
			@decH = ($contract);
		    } else {
			$contract = join(CODE_SEP, @decH[0,1]);
			exists $map-&gt;{$contract} and @decH = ($contract, $decH[2]);
		    }
		    # even if V's ignorable, LT contraction is not supported.
		    # If such a situation were required, NFD should be used.
		}
		if (@decH == 3 &amp;&amp; exists $max-&gt;{$decH[1]}) {
		    my $contract = join(CODE_SEP, @decH[1,2]);
		    exists $map-&gt;{$contract} and @decH = ($decH[0], $contract);
		}
	    }

	    @ce = map({
		    exists $map-&gt;{$_} ? @{ $map-&gt;{$_} } :
		$uXS &amp;&amp; _exists_simple($_) ? _fetch_simple($_) : ### XS only
		    $der-&gt;($_);
		} @decH);
	}
    } elsif ($out &amp;&amp; 0x10FFFF &lt; $u) {
	@ce = map _pack_override($_, $u, $der), $out-&gt;($u);
    } else {
	my $cjk  = $self-&gt;{overrideCJK};
	my $vers = $self-&gt;{UCA_Version};
	if ($cjk &amp;&amp; _isUIdeo($u, $vers)) {
	    @ce = map _pack_override($_, $u, $der), $cjk-&gt;($u);
	} elsif ($vers == 8 &amp;&amp; defined $cjk &amp;&amp; _isUIdeo($u, 0)) {
	    @ce = _uideoCE_8($u);
	} else {
	    @ce = $der-&gt;($u);
	}
    }
    return map $self-&gt;varCE($_), @ce;
}


##
## string sortkey = getSortKey(string arg)
##
sub getSortKey
{
    my $self = shift;
    my $orig = shift;
    my $str  = $self-&gt;process($orig);
    my $rEnt = $self-&gt;splitEnt($str); # get an arrayref of JCPS
    my $vers = $self-&gt;{UCA_Version};
    my $term = $self-&gt;{hangul_terminator};
    my $lev  = $self-&gt;{level};
    my $iden = $self-&gt;{identical};

    my @buf; # weight arrays
    if ($term) {
	my $preHST = '';
	my $termCE = $self-&gt;varCE(pack(VCE_TEMPLATE, NON_VAR, $term, 0,0,0));
	foreach my $jcps (@$rEnt) {
	    # weird things like VL, TL-contraction are not considered!
	    my $curHST = join '', map getHST($_, $vers), split /;/, $jcps;
	    if ($preHST &amp;&amp; !$curHST || # hangul before non-hangul
		$preHST =~ /L\z/ &amp;&amp; $curHST =~ /^T/ ||
		$preHST =~ /V\z/ &amp;&amp; $curHST =~ /^L/ ||
		$preHST =~ /T\z/ &amp;&amp; $curHST =~ /^[LV]/) {
		push @buf, $termCE;
	    }
	    $preHST = $curHST;
	    push @buf, $self-&gt;getWt($jcps);
	}
	push @buf, $termCE if $preHST; # end at hangul
    } else {
	foreach my $jcps (@$rEnt) {
	    push @buf, $self-&gt;getWt($jcps);
	}
    }

    my $rkey = $self-&gt;mk_SortKey(\@buf); ### XS only

    if ($iden || $vers &gt;= 26 &amp;&amp; $lev == MaxLevel) {
	$rkey .= LEVEL_SEP;
	$rkey .= pack(TIE_TEMPLATE, unpack_U($str)) if $iden;
    }
    return $rkey;
}


##
## int compare = cmp(string a, string b)
##
sub cmp { $_[0]-&gt;getSortKey($_[1]) cmp $_[0]-&gt;getSortKey($_[2]) }
sub eq  { $_[0]-&gt;getSortKey($_[1]) eq  $_[0]-&gt;getSortKey($_[2]) }
sub ne  { $_[0]-&gt;getSortKey($_[1]) ne  $_[0]-&gt;getSortKey($_[2]) }
sub lt  { $_[0]-&gt;getSortKey($_[1]) lt  $_[0]-&gt;getSortKey($_[2]) }
sub le  { $_[0]-&gt;getSortKey($_[1]) le  $_[0]-&gt;getSortKey($_[2]) }
sub gt  { $_[0]-&gt;getSortKey($_[1]) gt  $_[0]-&gt;getSortKey($_[2]) }
sub ge  { $_[0]-&gt;getSortKey($_[1]) ge  $_[0]-&gt;getSortKey($_[2]) }

##
## list[strings] sorted = sort(list[strings] arg)
##
sub sort {
    my $obj = shift;
    return
	map { $_-&gt;[1] }
	    sort{ $a-&gt;[0] cmp $b-&gt;[0] }
		map [ $obj-&gt;getSortKey($_), $_ ], @_;
}


##
## bool _nonIgnorAtLevel(arrayref weights, int level)
##
sub _nonIgnorAtLevel($$)
{
    my $wt = shift;
    return if ! defined $wt;
    my $lv = shift;
    return grep($wt-&gt;[$_-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 &gt;= @$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 weights?
	return if @{ $source-&gt;[$g] } != @{ $substr-&gt;[$g] };

	for my $w (0..@{ $substr-&gt;[$g] }-1) {
	    for my $v (0..$lev-1) {
		return if $source-&gt;[$g][$w][$v] != $substr-&gt;[$g][$w][$v];
	    }
	}
    }
    return 1;
}

##
## (int position, int length)
## int position = index(string, substring, position, [undoc'ed global])
##
## With "global" (only for the list context),
##  returns list of arrayref[position, length].
##
sub index
{
    my $self = shift;
    $self-&gt;{preprocess} and
	croak "Don't use Preprocess with index(), match(), etc.";
    $self-&gt;{normCode} and
	croak "Don't use Normalization with index(), match(), etc.";

    my $str  = shift;
    my $len  = length($str);
    my $sub  = shift;
    my $subE = $self-&gt;splitEnt($sub);
    my $pos  = @_ ? shift : 0;
       $pos  = 0 if $pos &lt; 0;
    my $glob = shift;

    my $lev  = $self-&gt;{level};
    my $v2i  = $self-&gt;{UCA_Version} &gt;= 9 &amp;&amp;
		$self-&gt;{variable} ne 'non-ignorable';

    if (! @$subE) {
	my $temp = $pos &lt;= 0 ? 0 : $len &lt;= $pos ? $len : $pos;
	return $glob
	    ? map([$_, 0], $temp..$len)
	    : wantarray ? ($temp,0) : $temp;
    }
    $len &lt; $pos
	and return wantarray ? () : NOMATCHPOS;
    my $strE = $self-&gt;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-&gt;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 &amp;&amp; !$var &amp;&amp; !$wt[0]) {
	    push @{ $subWt[-1] }, \@wt if $to_be_pushed;
	} elsif ($to_be_pushed) {
	    push @subWt, [ \@wt ];
	}
	# else ===&gt; skipped
    }

    my $count = 0;
    my $end = @$strE - 1;

    $last_is_variable = FALSE; # reuse
    for (my $i = 0; $i &lt;= $end; ) { # no $i++
	my $found_base = 0;

	# fetch a grapheme
	while ($i &lt;= $end &amp;&amp; $found_base == 0) {
	    for my $vwt ($self-&gt;getWt($strE-&gt;[$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 &amp;&amp; !$var &amp;&amp; !$wt[0]) {
		    push @{ $strWt[-1] }, \@wt if $to_be_pushed;
		    $finPos[-1] = $strE-&gt;[$i][2];
		} elsif ($to_be_pushed) {
		    push @strWt, [ \@wt ];
		    push @iniPos, $found_base ? NOMATCHPOS : $strE-&gt;[$i][1];
		    $finPos[-1] = NOMATCHPOS if $found_base;
		    push @finPos, $strE-&gt;[$i][2];
		    $found_base++;
		}
		# else ===&gt; no-op
	    }
	    $i++;
	}

	# try to match
	while ( @strWt &gt; @subWt || (@strWt == @subWt &amp;&amp; $i &gt; $end) ) {
	    if ($iniPos[0] != NOMATCHPOS &amp;&amp;
		    $finPos[$#subWt] != NOMATCHPOS &amp;&amp;
			_eqArray(\@strWt, \@subWt, $lev)) {
		my $temp = $iniPos[0] + $pos;

		if ($glob) {
		    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 $glob
	? @g_ret
	: wantarray ? () : NOMATCHPOS;
}

##
## scalarref to matching part = match(string, substring)
##
sub match
{
    my $self = shift;
    if (my($pos,$len) = $self-&gt;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, $_-&gt;[0], $_-&gt;[1]),
		$self-&gt;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-&gt;index($_[0], $_[1])) {
	if ($code) {
	    my $mat = substr($_[0], $pos, $len);
	    substr($_[0], $pos, $len, $code-&gt;($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-&gt;index($_[0], $_[1], 0, 'g')) {
	if ($code) {
	    my $mat = substr($_[0], $pos_len-&gt;[0], $pos_len-&gt;[1]);
	    substr($_[0], $pos_len-&gt;[0], $pos_len-&gt;[1], $code-&gt;($mat));
	} else {
	    substr($_[0], $pos_len-&gt;[0], $pos_len-&gt;[1], $_[2]);
	}
	$cnt++;
    }
    return $cnt;
}

1;
__END__

=head1 NAME

Unicode::Collate - Unicode Collation Algorithm

=head1 SYNOPSIS

  use Unicode::Collate;

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

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

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

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

=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&lt;new&gt; method returns a collator object. If new() is called
with no parameters, the collator should do the default collation.

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

=over 4

=item UCA_Version

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

The following revisions are supported.  The default is 43.

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

* See below for C&lt;long_contraction&gt; with C&lt;UCA_Version&gt; 22 and 24.

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

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

* Fully ignorable characters were ignored, and would not interrupt
contractions with C&lt;UCA_Version&gt; 9 and 11.

* Treatment of ignorables after variables and some behaviors
were changed at C&lt;UCA_Version&gt; 9.

* Characters regarded as CJK unified ideographs (cf. C&lt;overrideCJK&gt;)
depend on C&lt;UCA_Version&gt;.

* Many hangul jamo are assigned at C&lt;UCA_Version&gt; 20, that will affect
C&lt;hangul_terminator&gt;.

=item alternate

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

For backward compatibility, C&lt;alternate&gt; (old name) can be used
as an alias for C&lt;variable&gt;.

=item backwards

-- see 3.4 Backward Accents, UTS #10.

     backwards =&gt; $levelNumber or \@levelNumbers

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

=item entry

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

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

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

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

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

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

=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&lt;hangul_terminator&gt; 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&lt;the Unicode Standard&gt;
and F&lt;HangulSyllableType.txt&gt;.

B&lt;Implementation Note:&gt;
(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.

=item highestFFFF

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

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

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

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

=item identical

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

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

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

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

=item ignoreChar

=item ignoreName

-- see 3.6 Variable Weighting, UTS #10.

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

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

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

=item ignore_level2

-- see 5.1 Parametric Tailoring, UTS #10.

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

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

B&lt;NOTE&gt;: C&lt;level&gt; should be 3 or greater.

=item katakana_before_hiragana

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

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

B&lt;NOTE&gt;: 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 Sort Key, UTS #10.

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

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

  ex.level =&gt; 2,

If omitted, the maximum is the 4th.

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

See also C&lt;identical&gt;.

=item long_contraction

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

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

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

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

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

Under C&lt;(normalization =E&lt;gt&gt; undef)&gt;, detection step of discontiguous
contractions will be skipped.

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

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

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

=item minimalFFFE

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

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

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

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

=item normalization

-- see 4.1 Normalize, UTS #10.

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

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

C&lt;normalization&gt; is performed after C&lt;preprocess&gt; (if defined).

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

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

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

Except C&lt;(normalization =E&lt;gt&gt; undef)&gt;,
B&lt;Unicode::Normalize&gt; is required (see also B&lt;CAVEAT&gt;).

=item overrideCJK

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

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

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

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

Through C&lt;overrideCJK&gt;, ordering of CJK unified ideographs (including
extensions) can be overridden.

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

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

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

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

The return value may be a list containing zero or more of
an arrayref, an integer, or C&lt;undef&gt;.

ex. ignores all CJK unified ideographs.

  overrideCJK =&gt; sub {()}, # CODEREF returning empty list

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

If a false value (including C&lt;undef&gt;) is passed, C&lt;overrideCJK&gt;
has no effect.
C&lt;$Collator-E&lt;gt&gt;change(overrideCJK =E&lt;gt&gt; 0)&gt; resets the old one.

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

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

=item overrideHangul

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

By default, Hangul syllables are decomposed into Hangul Jamo,
even if C&lt;(normalization =E&lt;gt&gt; undef)&gt;.
But the mapping of Hangul syllables may be overridden.

This parameter works like C&lt;overrideCJK&gt;, so see there for examples.

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

If a false value (but not C&lt;undef&gt;) is passed, C&lt;overrideHangul&gt;
has no effect.
C&lt;$Collator-E&lt;gt&gt;change(overrideHangul =E&lt;gt&gt; 0)&gt; resets the old one.

If C&lt;undef&gt; 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 C&lt;table&gt; or C&lt;entry&gt; is still valid.

=item overrideOut

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

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

When C&lt;UCA_Version&gt; E&lt;gt&gt;= 22, the weights of out-of-range values
can be overridden. Though C&lt;table&gt; or C&lt;entry&gt; are available for them,
out-of-range values are too many.

C&lt;overrideOut&gt; can perform it algorithmically.
This parameter works like C&lt;overrideCJK&gt;, so see there for examples.

ex. ignores all out-of-range values.

  overrideOut =&gt; sub {()}, # CODEREF returning empty list

If a false value (including C&lt;undef&gt;) is passed, C&lt;overrideOut&gt;
has no effect.
C&lt;$Collator-E&lt;gt&gt;change(overrideOut =E&lt;gt&gt; 0)&gt; resets the old one.

B&lt;NOTE ABOUT U+FFFD:&gt;

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

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

  overrideOut =&gt; sub { 0xFFFD }, # CODEREF returning a very large integer

This workaround is unnecessary since Unicode 6.3.0.

=item preprocess

-- see 5.4 Preprocessing, UTS #10.

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

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

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

C&lt;preprocess&gt; is performed before C&lt;normalization&gt; (if defined).

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

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

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

=item rearrange

-- see 3.5 Rearrangement, UTS #10.

Characters that are not coded in logical order and to be rearranged.
If C&lt;UCA_Version&gt; is equal to or less than 11, default is:

    rearrange =&gt; [ 0x0E40..0x0E44, 0x0EC0..0x0EC4 ],

If you want to disallow any rearrangement, pass C&lt;undef&gt; or C&lt;[]&gt;
(a reference to empty list) as the value for this key.

If C&lt;UCA_Version&gt; is equal to or greater than 14, default is C&lt;[]&gt;
(i.e. no rearrangement).

B&lt;According to the version 9 of UCA, this parameter shall not be used;
but it is not warned at present.&gt;

=item rewrite

If specified, the coderef is used to rewrite lines in C&lt;table&gt; or C&lt;entry&gt;.
The coderef will get each line, and then should return a rewritten line
according to the UCA file format.
If the coderef returns an empty line, the line will be skipped.

e.g. any primary ignorable characters into tertiary ignorable:

    rewrite =&gt; sub {
        my $line = shift;
        $line =~ s/\[\.0000\..{4}\..{4}\./[.0000.0000.0000./g;
        return $line;
    },

This example shows rewriting weights. C&lt;rewrite&gt; is allowed to
affect code points, weights, and the name.

B&lt;NOTE&gt;: C&lt;table&gt; is available to use another table file;
preparing a modified table once would be more efficient than
rewriting lines on reading an unmodified table every time.

=item suppress

-- see 3.12 Special-Purpose Commands, UTS #35 (LDML) Part 5: Collation.

Contractions beginning with the specified characters are suppressed,
even if those contractions are defined in C&lt;table&gt;.

An example for Russian and some languages using the Cyrillic script:

    suppress =&gt; [0x0400..0x0417, 0x041A..0x0437, 0x043A..0x045F],

where 0x0400 stands for C&lt;U+0400&gt;, CYRILLIC CAPITAL LETTER IE WITH GRAVE.

B&lt;NOTE&gt;: Contractions via C&lt;entry&gt; will not be suppressed.

=item table

-- see 3.8 Default Unicode Collation Element Table, UTS #10.

You can use another collation element table if desired.

The table file should locate in the F&lt;Unicode/Collate&gt; directory
on C&lt;@INC&gt;. Say, if the filename is F&lt;Foo.txt&gt;,
the table file is searched as F&lt;Unicode/Collate/Foo.txt&gt; in C&lt;@INC&gt;.

By default, F&lt;allkeys.txt&gt; (as the filename of DUCET) is used.
If you will prepare your own table file, any name other than F&lt;allkeys.txt&gt;
may be better to avoid namespace conflict.

B&lt;NOTE&gt;: When XSUB is used, the DUCET is compiled on building this
module, and it may save time at the run time.
Explicit saying C&lt;(table =E&lt;gt&gt; 'allkeys.txt')&gt;, or using another table,
or using C&lt;ignoreChar&gt;, C&lt;ignoreName&gt;, C&lt;undefChar&gt;, C&lt;undefName&gt; or
C&lt;rewrite&gt; will prevent this module from using the compiled DUCET.

If C&lt;undef&gt; is passed explicitly as the value for this key,
no file is read (but you can define collation elements via C&lt;entry&gt;).

A typical way to define a collation element table
without any file of table:

   $onlyABC = Unicode::Collate-&gt;new(
       table =&gt; undef,
       entry =&gt; &lt;&lt; 'ENTRIES',
0061 ; [.0101.0020.0002.0061] # LATIN SMALL LETTER A
0041 ; [.0101.0020.0008.0041] # LATIN CAPITAL LETTER A
0062 ; [.0102.0020.0002.0062] # LATIN SMALL LETTER B
0042 ; [.0102.0020.0008.0042] # LATIN CAPITAL LETTER B
0063 ; [.0103.0020.0002.0063] # LATIN SMALL LETTER C
0043 ; [.0103.0020.0008.0043] # LATIN CAPITAL LETTER C
ENTRIES
    );

If C&lt;ignoreName&gt; or C&lt;undefName&gt; is used, character names should be
specified as a comment (following C&lt;#&gt;) on each line.

=item undefChar

=item undefName

-- see 6.3.3 Reducing the Repertoire, UTS #10.

Undefines the collation element as if it were unassigned in the C&lt;table&gt;.
This reduces the size of the table.
If an unassigned character appears in the string to be collated,
the sort key is made from its codepoint
as a single-character collation element,
as it is greater than any other assigned collation elements
(in the codepoint order among the unassigned characters).
But, it'd be better to ignore characters
unfamiliar to you and maybe never used.

Through C&lt;undefChar&gt;, any character matching C&lt;qr/$undefChar/&gt;
will be undefined. Through C&lt;undefName&gt;, any character whose name
(given in the C&lt;table&gt; file as a comment) matches C&lt;qr/$undefName/&gt;
will be undefined.

ex. Collation weights for beyond-BMP characters are not stored in object:

    undefChar =&gt; qr/[^\0-\x{fffd}]/,

=item upper_before_lower

-- see 6.6 Case Comparisons, UTS #10.

By default, lowercase is before uppercase.
If the parameter is made true, this is reversed.

B&lt;NOTE&gt;: 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.6 Variable Weighting, UTS #10.

This key allows for variable weighting of variable collation elements,
which are marked with an ASTERISK in the table
(NOTE: Many punctuation marks and symbols are variable in F&lt;allkeys.txt&gt;).

   variable =&gt; 'blanked', 'non-ignorable', 'shifted', or 'shift-trimmed'.

These names are case-insensitive.
By default (if specification is omitted), 'shifted' is adopted.

   'Blanked'        Variable elements are made ignorable at levels 1 through 3;
                    considered at the 4th level.

   'Non-Ignorable'  Variable elements are not reset to ignorable.

   'Shifted'        Variable elements are made ignorable at levels 1 through 3
                    their level 4 weight is replaced by the old level 1 weight.
                    Level 4 weight for Non-Variable elements is 0xFFFF.

   'Shift-Trimmed'  Same as 'shifted', but all FFFF's at the 4th level
                    are trimmed.

=back

=head2 Methods for Collation

=over 4

=item C&lt;@sorted = $Collator-E&lt;gt&gt;sort(@not_sorted)&gt;

Sorts a list of strings.

=item C&lt;$result = $Collator-E&lt;gt&gt;cmp($a, $b)&gt;

Returns 1 (when C&lt;$a&gt; is greater than C&lt;$b&gt;)
or 0 (when C&lt;$a&gt; is equal to C&lt;$b&gt;)
or -1 (when C&lt;$a&gt; is less than C&lt;$b&gt;).

=item C&lt;$result = $Collator-E&lt;gt&gt;eq($a, $b)&gt;

=item C&lt;$result = $Collator-E&lt;gt&gt;ne($a, $b)&gt;

=item C&lt;$result = $Collator-E&lt;gt&gt;lt($a, $b)&gt;

=item C&lt;$result = $Collator-E&lt;gt&gt;le($a, $b)&gt;

=item C&lt;$result = $Collator-E&lt;gt&gt;gt($a, $b)&gt;

=item C&lt;$result = $Collator-E&lt;gt&gt;ge($a, $b)&gt;

They works like the same name operators as theirs.

   eq : whether $a is equal to $b.
   ne : whether $a is not equal to $b.
   lt : whether $a is less than $b.
   le : whether $a is less than $b or equal to $b.
   gt : whether $a is greater than $b.
   ge : whether $a is greater than $b or equal to $b.

=item C&lt;$sortKey = $Collator-E&lt;gt&gt;getSortKey($string)&gt;

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

Returns a sort key.

You compare the sort keys using a binary comparison
and get the result of the comparison of the strings using UCA.

   $Collator-&gt;getSortKey($a) cmp $Collator-&gt;getSortKey($b)

      is equivalent to

   $Collator-&gt;cmp($a, $b)

=item C&lt;$sortKeyForm = $Collator-E&lt;gt&gt;viewSortKey($string)&gt;

Converts a sorting key into its representation form.
If C&lt;UCA_Version&gt; is 8, the output is slightly different.

   use Unicode::Collate;
   my $c = Unicode::Collate-&gt;new();
   print $c-&gt;viewSortKey("Perl"),"\n";

   # output:
   # [0B67 0A65 0B7F 0B03 | 0020 0020 0020 0020 | 0008 0002 0002 0002 | FFFF FFFF FFFF FFFF]
   #  Level 1               Level 2               Level 3               Level 4

=back

=head2 Methods for Searching

The C&lt;match&gt;, C&lt;gmatch&gt;, C&lt;subst&gt;, C&lt;gsubst&gt; methods work
like C&lt;m//&gt;, C&lt;m//g&gt;, C&lt;s///&gt;, C&lt;s///g&gt;, respectively,
but they are not aware of any pattern, but only a literal substring.

B&lt;DISCLAIMER:&gt; If C&lt;preprocess&gt; or C&lt;normalization&gt; parameter is true
for C&lt;$Collator&gt;, calling these methods (C&lt;index&gt;, C&lt;match&gt;, C&lt;gmatch&gt;,
C&lt;subst&gt;, C&lt;gsubst&gt;) is croaked, as the position and the length might
differ from those on the specified string.

C&lt;rearrange&gt; and C&lt;hangul_terminator&gt; parameters are neglected.
C&lt;katakana_before_hiragana&gt; and C&lt;upper_before_lower&gt; don't affect
matching and searching, as it doesn't matter whether greater or less.

=over 4

=item C&lt;$position = $Collator-E&lt;gt&gt;index($string, $substring[, $position])&gt;

=item C&lt;($position, $length) = $Collator-E&lt;gt&gt;index($string, $substring[, $position])&gt;

If C&lt;$substring&gt; matches a part of C&lt;$string&gt;, returns
the position of the first occurrence of the matching part in scalar context;
in list context, returns a two-element list of
the position and the length of the matching part.

If C&lt;$substring&gt; does not match any part of C&lt;$string&gt;,
returns C&lt;-1&gt; in scalar context and
an empty list in list context.

e.g. when the content of C&lt;$str&gt; is C&lt;"Ich mu&gt;E&lt;szlig&gt;C&lt; studieren Perl."&gt;,
you say the following where C&lt;$sub&gt; is C&lt;"M&gt;E&lt;uuml&gt;C&lt;SS"&gt;,

  my $Collator = Unicode::Collate-&gt;new( normalization =&gt; undef, level =&gt; 1 );
                                     # (normalization =&gt; undef) is REQUIRED.
  my $match;
  if (my($pos,$len) = $Collator-&gt;index($str, $sub)) {
      $match = substr($str, $pos, $len);
  }

and get C&lt;"mu&gt;E&lt;szlig&gt;C&lt;"&gt; in C&lt;$match&gt;, since C&lt;"mu&gt;E&lt;szlig&gt;C&lt;"&gt;
is primary equal to C&lt;"M&gt;E&lt;uuml&gt;C&lt;SS"&gt;.

=item C&lt;$match_ref = $Collator-E&lt;gt&gt;match($string, $substring)&gt;

=item C&lt;($match)   = $Collator-E&lt;gt&gt;match($string, $substring)&gt;

If C&lt;$substring&gt; matches a part of C&lt;$string&gt;, in scalar context, returns
B&lt;a reference to&gt; the first occurrence of the matching part
(C&lt;$match_ref&gt; is always true if matches,
since every reference is B&lt;true&gt;);
in list context, returns the first occurrence of the matching part.

If C&lt;$substring&gt; does not match any part of C&lt;$string&gt;,
returns C&lt;undef&gt; in scalar context and
an empty list in list context.

e.g.

    if ($match_ref = $Collator-&gt;match($str, $sub)) { # scalar context
	print "matches [$$match_ref].\n";
    } else {
	print "doesn't match.\n";
    }

     or

    if (($match) = $Collator-&gt;match($str, $sub)) { # list context
	print "matches [$match].\n";
    } else {
	print "doesn't match.\n";
    }

=item C&lt;@match = $Collator-E&lt;gt&gt;gmatch($string, $substring)&gt;

If C&lt;$substring&gt; matches a part of C&lt;$string&gt;, returns
all the matching parts (or matching count in scalar context).

If C&lt;$substring&gt; does not match any part of C&lt;$string&gt;,
returns an empty list.

=item C&lt;$count = $Collator-E&lt;gt&gt;subst($string, $substring, $replacement)&gt;

If C&lt;$substring&gt; matches a part of C&lt;$string&gt;,
the first occurrence of the matching part is replaced by C&lt;$replacement&gt;
(C&lt;$string&gt; is modified) and C&lt;$count&gt; (always equals to C&lt;1&gt;) is returned.

C&lt;$replacement&gt; can be a C&lt;CODEREF&gt;,
taking the matching part as an argument,
and returning a string to replace the matching part
(a bit similar to C&lt;s/(..)/$coderef-E&lt;gt&gt;($1)/e&gt;).

=item C&lt;$count = $Collator-E&lt;gt&gt;gsubst($string, $substring, $replacement)&gt;

If C&lt;$substring&gt; matches a part of C&lt;$string&gt;,
all the occurrences of the matching part are replaced by C&lt;$replacement&gt;
(C&lt;$string&gt; is modified) and C&lt;$count&gt; is returned.

C&lt;$replacement&gt; can be a C&lt;CODEREF&gt;,
taking the matching part as an argument,
and returning a string to replace the matching part
(a bit similar to C&lt;s/(..)/$coderef-E&lt;gt&gt;($1)/eg&gt;).

e.g.

  my $Collator = Unicode::Collate-&gt;new( normalization =&gt; undef, level =&gt; 1 );
                                     # (normalization =&gt; undef) is REQUIRED.
  my $str = "Camel donkey zebra came\x{301}l CAMEL horse cam\0e\0l...";
  $Collator-&gt;gsubst($str, "camel", sub { "&lt;b&gt;$_[0]&lt;/b&gt;" });

  # now $str is "&lt;b&gt;Camel&lt;/b&gt; donkey zebra &lt;b&gt;came\x{301}l&lt;/b&gt; &lt;b&gt;CAMEL&lt;/b&gt; horse &lt;b&gt;cam\0e\0l&lt;/b&gt;...";
  # i.e., all the camels are made bold-faced.

   Examples: levels and ignore_level2 - what does camel match?
  ---------------------------------------------------------------------------
   level  ignore_level2  |  camel  Camel  came\x{301}l  c-a-m-e-l  cam\0e\0l
  -----------------------|---------------------------------------------------
     1        false      |   yes    yes      yes          yes        yes
     2        false      |   yes    yes      no           yes        yes
     3        false      |   yes    no       no           yes        yes
     4        false      |   yes    no       no           no         yes
  -----------------------|---------------------------------------------------
     1        true       |   yes    yes      yes          yes        yes
     2        true       |   yes    yes      yes          yes        yes
     3        true       |   yes    no       yes          yes        yes
     4        true       |   yes    no       yes          no         yes
  ---------------------------------------------------------------------------
   note: if variable =&gt; non-ignorable, camel doesn't match c-a-m-e-l
         at any level.

=back

=head2 Other Methods

=over 4

=item C&lt;%old_tailoring = $Collator-E&lt;gt&gt;change(%new_tailoring)&gt;

=item C&lt;$modified_collator = $Collator-E&lt;gt&gt;change(%new_tailoring)&gt;

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

    $Collator = Unicode::Collate-&gt;new(level =&gt; 4);

    $Collator-&gt;eq("perl", "PERL"); # false

    %old = $Collator-&gt;change(level =&gt; 2); # returns (level =&gt; 4).

    $Collator-&gt;eq("perl", "PERL"); # true

    $Collator-&gt;change(%old); # returns (level =&gt; 2).

    $Collator-&gt;eq("perl", "PERL"); # false

Not all C&lt;(key,value)&gt;s are allowed to be changed.
See also C&lt;@Unicode::Collate::ChangeOK&gt; and C&lt;@Unicode::Collate::ChangeNG&gt;.

In the scalar context, returns the modified collator
(but it is B&lt;not&gt; a clone from the original).

    $Collator-&gt;change(level =&gt; 2)-&gt;eq("perl", "PERL"); # true

    $Collator-&gt;eq("perl", "PERL"); # true; now max level is 2nd.

    $Collator-&gt;change(level =&gt; 4)-&gt;eq("perl", "PERL"); # false

=item C&lt;$version = $Collator-E&lt;gt&gt;version()&gt;

Returns the version number (a string) of the Unicode Standard
which the C&lt;table&gt; file used by the collator object is based on.
If the table does not include a version line (starting with C&lt;@version&gt;),
returns C&lt;"unknown"&gt;.

=item C&lt;UCA_Version()&gt;

Returns the revision number of UTS #10 this module consults,
that should correspond with the DUCET incorporated.

=item C&lt;Base_Unicode_Version()&gt;

Returns the version number of UTS #10 this module consults,
that should correspond with the DUCET incorporated.

=back

=head1 EXPORT

No method will be exported.

=head1 INSTALL

Though this module can be used without any C&lt;table&gt; file,
to use this module easily, it is recommended to install a table file
in the UCA format, by copying it under the directory
&lt;a place in @INC&gt;/Unicode/Collate.

The most preferable one is "The Default Unicode Collation Element Table"
(aka DUCET), available from the Unicode Consortium's website:

   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 &lt;a place in @INC&gt;/Unicode/Collate/allkeys.txt
manually.

=head1 CAVEATS

=over 4

=item Normalization

Use of the C&lt;normalization&gt; parameter requires the B&lt;Unicode::Normalize&gt;
module (see L&lt;Unicode::Normalize&gt;).

If you need not it (say, in the case when you need not
handle any combining characters),
assign C&lt;(normalization =E&lt;gt&gt; undef)&gt; explicitly.

-- see 6.5 Avoiding Normalization, UTS #10.

=item Conformance Test

The Conformance Test for the UCA is available
under L&lt;http://www.unicode.org/Public/UCA/&gt;.

For F&lt;CollationTest_SHIFTED.txt&gt;,
a collator via C&lt;Unicode::Collate-E&lt;gt&gt;new( )&gt; should be used;
for F&lt;CollationTest_NON_IGNORABLE.txt&gt;, a collator via
C&lt;Unicode::Collate-E&lt;gt&gt;new(variable =E&lt;gt&gt; "non-ignorable", level =E&lt;gt&gt; 3)&gt;.

If C&lt;UCA_Version&gt; is 26 or later, the C&lt;identical&gt; level is preferred;
C&lt;Unicode::Collate-E&lt;gt&gt;new(identical =E&lt;gt&gt; 1)&gt; and
C&lt;Unicode::Collate-E&lt;gt&gt;new(identical =E&lt;gt&gt; 1,&gt;
C&lt;variable =E&lt;gt&gt; "non-ignorable", level =E&lt;gt&gt; 3)&gt; should be used.

B&lt;Unicode::Normalize is required to try The Conformance Test.&gt;

B&lt;EBCDIC-SUPPORT IS EXPERIMENTAL.&gt;

=back

=head1 AUTHOR, COPYRIGHT AND LICENSE

The Unicode::Collate module for perl was written by SADAHIRO Tomoyuki,
&lt;SADAHIRO@cpan.org&gt;. This module is Copyright(C) 2001-2021,
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.

The file Unicode/Collate/allkeys.txt was copied verbatim
from L&lt;http://www.unicode.org/Public/UCA/13.0.0/allkeys.txt&gt;.
For this file, Copyright (c) 2020 Unicode, Inc.; distributed
under the Terms of Use in L&lt;http://www.unicode.org/terms_of_use.html&gt;

=head1 SEE ALSO

=over 4

=item Unicode Collation Algorithm - UTS #10

L&lt;http://www.unicode.org/reports/tr10/&gt;

=item The Default Unicode Collation Element Table (DUCET)

L&lt;http://www.unicode.org/Public/UCA/latest/allkeys.txt&gt;

=item The conformance test for the UCA

L&lt;http://www.unicode.org/Public/UCA/latest/CollationTest.html&gt;

L&lt;http://www.unicode.org/Public/UCA/latest/CollationTest.zip&gt;

=item Hangul Syllable Type

L&lt;http://www.unicode.org/Public/UNIDATA/HangulSyllableType.txt&gt;

=item Unicode Normalization Forms - UAX #15

L&lt;http://www.unicode.org/reports/tr15/&gt;

=item Unicode Locale Data Markup Language (LDML) - UTS #35

L&lt;http://www.unicode.org/reports/tr35/&gt;

=back

=cut
</pre></body></html>