5 no warnings 'surrogate'; # surrogates can be inputs to this
12 our @ISA = qw(Exporter);
14 our @EXPORT_OK = qw(charinfo
16 charblocks charscripts
18 general_categories bidi_types
20 casefold all_casefolds casespec
33 sub IS_ASCII_PLATFORM { ord("A") == 65 }
37 Unicode::UCD - Unicode character database
41 use Unicode::UCD 'charinfo';
42 my $charinfo = charinfo($codepoint);
44 use Unicode::UCD 'casefold';
45 my $casefold = casefold(0xFB00);
47 use Unicode::UCD 'all_casefolds';
48 my $all_casefolds_ref = all_casefolds();
50 use Unicode::UCD 'casespec';
51 my $casespec = casespec(0xFB00);
53 use Unicode::UCD 'charblock';
54 my $charblock = charblock($codepoint);
56 use Unicode::UCD 'charscript';
57 my $charscript = charscript($codepoint);
59 use Unicode::UCD 'charblocks';
60 my $charblocks = charblocks();
62 use Unicode::UCD 'charscripts';
63 my $charscripts = charscripts();
65 use Unicode::UCD qw(charscript charinrange);
66 my $range = charscript($script);
67 print "looks like $script\n" if charinrange($range, $codepoint);
69 use Unicode::UCD qw(general_categories bidi_types);
70 my $categories = general_categories();
71 my $types = bidi_types();
73 use Unicode::UCD 'prop_aliases';
74 my @space_names = prop_aliases("space");
76 use Unicode::UCD 'prop_value_aliases';
77 my @gc_punct_names = prop_value_aliases("Gc", "Punct");
79 use Unicode::UCD 'prop_invlist';
80 my @puncts = prop_invlist("gc=punctuation");
82 use Unicode::UCD 'prop_invmap';
83 my ($list_ref, $map_ref, $format, $missing)
84 = prop_invmap("General Category");
86 use Unicode::UCD 'search_invlist';
87 my $index = search_invlist(\@invlist, $code_point);
89 use Unicode::UCD 'compexcl';
90 my $compexcl = compexcl($codepoint);
92 use Unicode::UCD 'namedseq';
93 my $namedseq = namedseq($named_sequence_name);
95 my $unicode_version = Unicode::UCD::UnicodeVersion();
97 my $convert_to_numeric =
98 Unicode::UCD::num("\N{RUMI DIGIT ONE}\N{RUMI DIGIT TWO}");
102 The Unicode::UCD module offers a series of functions that
103 provide a simple interface to the Unicode
106 =head2 code point argument
108 Some of the functions are called with a I<code point argument>, which is either
109 a decimal or a hexadecimal scalar designating a code point in the platform's
110 native character set (extended to Unicode), or C<U+> followed by hexadecimals
111 designating a Unicode code point. A leading 0 will force a hexadecimal
112 interpretation, as will a hexadecimal digit that isn't a decimal digit.
116 223 # Decimal 223 in native character set
117 0223 # Hexadecimal 223, native (= 547 decimal)
118 0xDF # Hexadecimal DF, native (= 223 decimal
119 U+DF # Hexadecimal DF, in Unicode's character set
120 (= LATIN SMALL LETTER SHARP S)
122 Note that the largest code point in Unicode is U+10FFFF.
131 my $v_unicode_version; # v-string.
134 my ($rfh, @path) = @_;
136 unless (defined $$rfh) {
139 $f = File::Spec->catfile($d, "unicore", @path);
140 last if open($$rfh, $f);
143 croak __PACKAGE__, ": failed to find ",
144 File::Spec->catfile(@path), " in @INC"
150 sub _dclone ($) { # Use Storable::dclone if available; otherwise emulate it.
152 use if defined &DynaLoader::boot_DynaLoader, Storable => qw(dclone);
154 return dclone(shift) if defined &dclone;
158 return $arg unless $type; # No deep cloning needed for scalars
160 if ($type eq 'ARRAY') {
162 foreach my $element (@$arg) {
163 push @return, &_dclone($element);
167 elsif ($type eq 'HASH') {
169 foreach my $key (keys %$arg) {
170 $return{$key} = &_dclone($arg->{$key});
175 croak "_dclone can't handle " . $type;
181 use Unicode::UCD 'charinfo';
183 my $charinfo = charinfo(0x41);
185 This returns information about the input L</code point argument>
186 as a reference to a hash of fields as defined by the Unicode
187 standard. If the L</code point argument> is not assigned in the standard
188 (i.e., has the general category C<Cn> meaning C<Unassigned>)
189 or is a non-character (meaning it is guaranteed to never be assigned in
191 C<undef> is returned.
193 Fields that aren't applicable to the particular code point argument exist in the
194 returned hash, and are empty.
196 The keys in the hash with the meanings of their values are:
202 the input native L</code point argument> expressed in hexadecimal, with
204 added if necessary to make it contain at least four hexdigits
208 name of I<code>, all IN UPPER CASE.
209 Some control-type code points do not have names.
210 This field will be empty for C<Surrogate> and C<Private Use> code points,
211 and for the others without a name,
212 it will contain a description enclosed in angle brackets, like
213 C<E<lt>controlE<gt>>.
218 The short name of the general category of I<code>.
219 This will match one of the keys in the hash returned by L</general_categories()>.
221 The L</prop_value_aliases()> function can be used to get all the synonyms
222 of the category name.
226 the combining class number for I<code> used in the Canonical Ordering Algorithm.
227 For Unicode 5.1, this is described in Section 3.11 C<Canonical Ordering Behavior>
229 L<http://www.unicode.org/versions/Unicode5.1.0/>
231 The L</prop_value_aliases()> function can be used to get all the synonyms
232 of the combining class number.
236 bidirectional type of I<code>.
237 This will match one of the keys in the hash returned by L</bidi_types()>.
239 The L</prop_value_aliases()> function can be used to get all the synonyms
240 of the bidi type name.
242 =item B<decomposition>
244 is empty if I<code> has no decomposition; or is one or more codes
245 (separated by spaces) that, taken in order, represent a decomposition for
246 I<code>. Each has at least four hexdigits.
247 The codes may be preceded by a word enclosed in angle brackets, then a space,
248 like C<E<lt>compatE<gt> >, giving the type of decomposition
250 This decomposition may be an intermediate one whose components are also
251 decomposable. Use L<Unicode::Normalize> to get the final decomposition.
255 if I<code> represents a decimal digit this is its integer numeric value
259 if I<code> represents some other digit-like number, this is its integer
264 if I<code> represents a whole or rational number, this is its numeric value.
265 Rational values are expressed as a string like C<1/4>.
269 C<Y> or C<N> designating if I<code> is mirrored in bidirectional text
273 name of I<code> in the Unicode 1.0 standard if one
274 existed for this code point and is different from the current name
278 As of Unicode 6.0, this is always empty.
282 is empty if there is no single code point uppercase mapping for I<code>
283 (its uppercase mapping is itself);
284 otherwise it is that mapping expressed as at least four hexdigits.
285 (L</casespec()> should be used in addition to B<charinfo()>
286 for case mappings when the calling program can cope with multiple code point
291 is empty if there is no single code point lowercase mapping for I<code>
292 (its lowercase mapping is itself);
293 otherwise it is that mapping expressed as at least four hexdigits.
294 (L</casespec()> should be used in addition to B<charinfo()>
295 for case mappings when the calling program can cope with multiple code point
300 is empty if there is no single code point titlecase mapping for I<code>
301 (its titlecase mapping is itself);
302 otherwise it is that mapping expressed as at least four hexdigits.
303 (L</casespec()> should be used in addition to B<charinfo()>
304 for case mappings when the calling program can cope with multiple code point
309 the block I<code> belongs to (used in C<\p{Blk=...}>).
310 See L</Blocks versus Scripts>.
315 the script I<code> belongs to.
316 See L</Blocks versus Scripts>.
320 Note that you cannot do (de)composition and casing based solely on the
321 I<decomposition>, I<combining>, I<lower>, I<upper>, and I<title> fields;
322 you will need also the L</compexcl()>, and L</casespec()> functions.
326 # NB: This function is nearly duplicated in charnames.pm
330 if ($arg =~ /^[1-9]\d*$/) {
333 elsif ($arg =~ /^(?:0[xX])?([[:xdigit:]]+)$/) {
334 return CORE::hex($1);
336 elsif ($arg =~ /^[Uu]\+([[:xdigit:]]+)$/) { # Is of form U+0000, means
337 # wants the Unicode code
338 # point, not the native one
339 my $decimal = CORE::hex($1);
340 return $decimal if IS_ASCII_PLATFORM;
341 return utf8::unicode_to_native($decimal);
347 # Populated by _num. Converts real number back to input rational
348 my %real_to_rational;
350 # To store the contents of files found on disk.
363 # This function has traditionally mimicked what is in UnicodeData.txt,
364 # warts and all. This is a re-write that avoids UnicodeData.txt so that
365 # it can be removed to save disk space. Instead, this assembles
366 # information gotten by other methods that get data from various other
367 # files. It uses charnames to get the character name; and various
370 use feature 'unicode_strings';
372 # Will fail if called under minitest
373 use if defined &DynaLoader::boot_DynaLoader, "Unicode::Normalize" => qw(getCombinClass NFD);
376 my $code = _getcode($arg);
377 croak __PACKAGE__, "::charinfo: unknown code '$arg'" unless defined $code;
379 # Non-unicode implies undef.
380 return if $code > 0x10FFFF;
383 my $char = chr($code);
385 @CATEGORIES =_read_table("To/Gc.pl") unless @CATEGORIES;
386 $prop{'category'} = _search(\@CATEGORIES, 0, $#CATEGORIES, $code)
387 // $utf8::SwashInfo{'ToGc'}{'missing'};
389 return if $prop{'category'} eq 'Cn'; # Unassigned code points are undef
391 $prop{'code'} = sprintf "%04X", $code;
392 $prop{'name'} = ($char =~ /\p{Cntrl}/) ? '<control>'
393 : (charnames::viacode($code) // "");
395 $prop{'combining'} = getCombinClass($code);
397 @BIDIS =_read_table("To/Bc.pl") unless @BIDIS;
398 $prop{'bidi'} = _search(\@BIDIS, 0, $#BIDIS, $code)
399 // $utf8::SwashInfo{'ToBc'}{'missing'};
401 # For most code points, we can just read in "unicore/Decomposition.pl", as
402 # its contents are exactly what should be output. But that file doesn't
403 # contain the data for the Hangul syllable decompositions, which can be
404 # algorithmically computed, and NFD() does that, so we call NFD() for
405 # those. We can't use NFD() for everything, as it does a complete
406 # recursive decomposition, and what this function has always done is to
407 # return what's in UnicodeData.txt which doesn't show that recursiveness.
408 # Fortunately, the NFD() of the Hanguls doesn't have any recursion
410 # Having no decomposition implies an empty field; otherwise, all but
411 # "Canonical" imply a compatible decomposition, and the type is prefixed
412 # to that, as it is in UnicodeData.txt
413 UnicodeVersion() unless defined $v_unicode_version;
414 if ($v_unicode_version ge v2.0.0 && $char =~ /\p{Block=Hangul_Syllables}/) {
415 # The code points of the decomposition are output in standard Unicode
416 # hex format, separated by blanks.
417 $prop{'decomposition'} = join " ", map { sprintf("%04X", $_)}
418 unpack "U*", NFD($char);
421 @DECOMPOSITIONS = _read_table("Decomposition.pl")
422 unless @DECOMPOSITIONS;
423 $prop{'decomposition'} = _search(\@DECOMPOSITIONS, 0, $#DECOMPOSITIONS,
427 # Can use num() to get the numeric values, if any.
428 if (! defined (my $value = num($char))) {
429 $prop{'decimal'} = $prop{'digit'} = $prop{'numeric'} = "";
433 $prop{'decimal'} = $prop{'digit'} = $prop{'numeric'} = $value;
437 # For non-decimal-digits, we have to read in the Numeric type
438 # to distinguish them. It is not just a matter of integer vs.
439 # rational, as some whole number values are not considered digits,
440 # e.g., TAMIL NUMBER TEN.
441 $prop{'decimal'} = "";
443 @NUMERIC_TYPES =_read_table("To/Nt.pl") unless @NUMERIC_TYPES;
444 if ((_search(\@NUMERIC_TYPES, 0, $#NUMERIC_TYPES, $code) // "")
447 $prop{'digit'} = $prop{'numeric'} = $value;
451 $prop{'numeric'} = $real_to_rational{$value} // $value;
456 $prop{'mirrored'} = ($char =~ /\p{Bidi_Mirrored}/) ? 'Y' : 'N';
458 %UNICODE_1_NAMES =_read_table("To/Na1.pl", "use_hash") unless %UNICODE_1_NAMES;
459 $prop{'unicode10'} = $UNICODE_1_NAMES{$code} // "";
461 UnicodeVersion() unless defined $v_unicode_version;
462 if ($v_unicode_version ge v6.0.0) {
463 $prop{'comment'} = "";
466 %ISO_COMMENT = _read_table("To/Isc.pl", "use_hash") unless %ISO_COMMENT;
467 $prop{'comment'} = (defined $ISO_COMMENT{$code})
468 ? $ISO_COMMENT{$code}
472 %SIMPLE_UPPER = _read_table("To/Uc.pl", "use_hash") unless %SIMPLE_UPPER;
473 $prop{'upper'} = (defined $SIMPLE_UPPER{$code})
474 ? sprintf("%04X", $SIMPLE_UPPER{$code})
477 %SIMPLE_LOWER = _read_table("To/Lc.pl", "use_hash") unless %SIMPLE_LOWER;
478 $prop{'lower'} = (defined $SIMPLE_LOWER{$code})
479 ? sprintf("%04X", $SIMPLE_LOWER{$code})
482 %SIMPLE_TITLE = _read_table("To/Tc.pl", "use_hash") unless %SIMPLE_TITLE;
483 $prop{'title'} = (defined $SIMPLE_TITLE{$code})
484 ? sprintf("%04X", $SIMPLE_TITLE{$code})
487 $prop{block} = charblock($code);
488 $prop{script} = charscript($code);
492 sub _search { # Binary search in a [[lo,hi,prop],[...],...] table.
493 my ($table, $lo, $hi, $code) = @_;
497 my $mid = int(($lo+$hi) / 2);
499 if ($table->[$mid]->[0] < $code) {
500 if ($table->[$mid]->[1] >= $code) {
501 return $table->[$mid]->[2];
503 _search($table, $mid + 1, $hi, $code);
505 } elsif ($table->[$mid]->[0] > $code) {
506 _search($table, $lo, $mid - 1, $code);
508 return $table->[$mid]->[2];
512 sub _read_table ($;$) {
514 # Returns the contents of the mktables generated table file located at $1
515 # in the form of either an array of arrays or a hash, depending on if the
516 # optional second parameter is true (for hash return) or not. In the case
517 # of a hash return, each key is a code point, and its corresponding value
518 # is what the table gives as the code point's corresponding value. In the
519 # case of an array return, each outer array denotes a range with [0] the
520 # start point of that range; [1] the end point; and [2] the value that
521 # every code point in the range has. The hash return is useful for fast
522 # lookup when the table contains only single code point ranges. The array
523 # return takes much less memory when there are large ranges.
525 # This function has the side effect of setting
526 # $utf8::SwashInfo{$property}{'format'} to be the mktables format of the
528 # $utf8::SwashInfo{$property}{'missing'} to be the value for all entries
529 # not listed in the table.
530 # where $property is the Unicode property name, preceded by 'To' for map
531 # properties., e.g., 'ToSc'.
533 # Table entries look like one of:
534 # 0000 0040 Common # [65]
538 my $return_hash = shift;
539 $return_hash = 0 unless defined $return_hash;
543 my $list = do "unicore/$table";
545 # Look up if this property requires adjustments, which we do below if it
547 require "unicore/Heavy.pl";
548 my $property = $table =~ s/\.pl//r;
549 $property = $utf8::file_to_swash_name{$property};
550 my $to_adjust = defined $property
551 && $utf8::SwashInfo{$property}{'format'} =~ / ^ a /x;
553 for (split /^/m, $list) {
554 my ($start, $end, $value) = / ^ (.+?) \t (.*?) \t (.+?)
555 \s* ( \# .* )? # Optional comment
557 my $decimal_start = hex $start;
558 my $decimal_end = ($end eq "") ? $decimal_start : hex $end;
559 $value = hex $value if $to_adjust
560 && $utf8::SwashInfo{$property}{'format'} eq 'ax';
562 foreach my $i ($decimal_start .. $decimal_end) {
563 $return{$i} = ($to_adjust)
564 ? $value + $i - $decimal_start
570 && $return[-1][1] == $decimal_start - 1
571 && $return[-1][2] eq $value)
573 # If this is merely extending the previous range, do just that.
574 $return[-1]->[1] = $decimal_end;
577 push @return, [ $decimal_start, $decimal_end, $value ];
580 return ($return_hash) ? %return : @return;
584 my ($range, $arg) = @_;
585 my $code = _getcode($arg);
586 croak __PACKAGE__, "::charinrange: unknown code '$arg'"
587 unless defined $code;
588 _search($range, 0, $#$range, $code);
591 =head2 B<charblock()>
593 use Unicode::UCD 'charblock';
595 my $charblock = charblock(0x41);
596 my $charblock = charblock(1234);
597 my $charblock = charblock(0x263a);
598 my $charblock = charblock("U+263a");
600 my $range = charblock('Armenian');
602 With a L</code point argument> C<charblock()> returns the I<block> the code point
603 belongs to, e.g. C<Basic Latin>. The old-style block name is returned (see
604 L</Old-style versus new-style block names>).
605 If the code point is unassigned, this returns the block it would belong to if
606 it were assigned. (If the Unicode version being used is so early as to not
607 have blocks, all code points are considered to be in C<No_Block>.)
609 See also L</Blocks versus Scripts>.
611 If supplied with an argument that can't be a code point, C<charblock()> tries to
612 do the opposite and interpret the argument as an old-style block name. On an
613 ASCII platform, the return value is a I<range set> with one range: an
614 anonymous list with a single element that consists of another anonymous list
615 whose first element is the first code point in the block, and whose second
616 element is the final code point in the block. On an EBCDIC
617 platform, the first two Unicode blocks are not contiguous. Their range sets
618 are lists containing I<start-of-range>, I<end-of-range> code point pairs. You
619 can test whether a code point is in a range set using the L</charinrange()>
620 function. (To be precise, each I<range set> contains a third array element,
621 after the range boundary ones: the old_style block name.)
623 If the argument to C<charblock()> is not a known block, C<undef> is
633 # Can't read from the mktables table because it loses the hyphens in the
636 UnicodeVersion() unless defined $v_unicode_version;
637 if ($v_unicode_version lt v2.0.0) {
638 my $subrange = [ 0, 0x10FFFF, 'No_Block' ];
639 push @BLOCKS, $subrange;
640 push @{$BLOCKS{'No_Block'}}, $subrange;
642 elsif (openunicode(\$BLOCKSFH, "Blocks.txt")) {
645 while (<$BLOCKSFH>) {
646 if (/^([0-9A-F]+)\.\.([0-9A-F]+);\s+(.+)/) {
647 my ($lo, $hi) = (hex($1), hex($2));
648 my $subrange = [ $lo, $hi, $3 ];
649 push @BLOCKS, $subrange;
650 push @{$BLOCKS{$3}}, $subrange;
654 if (! IS_ASCII_PLATFORM) {
655 # The first two blocks, through 0xFF, are wrong on EBCDIC
658 my @new_blocks = _read_table("To/Blk.pl");
660 # Get rid of the first two ranges in the Unicode version, and
661 # replace them with the ones computed by mktables.
664 delete $BLOCKS{'Basic Latin'};
665 delete $BLOCKS{'Latin-1 Supplement'};
667 # But there are multiple entries in the computed versions, and
668 # we change their names to (which we know) to be the old-style
670 for my $i (0.. @new_blocks - 1) {
671 if ($new_blocks[$i][2] =~ s/Basic_Latin/Basic Latin/
672 or $new_blocks[$i][2] =~
673 s/Latin_1_Supplement/Latin-1 Supplement/)
675 push @{$BLOCKS{$new_blocks[$i][2]}}, $new_blocks[$i];
678 splice @new_blocks, $i;
682 unshift @BLOCKS, @new_blocks;
691 _charblocks() unless @BLOCKS;
693 my $code = _getcode($arg);
696 my $result = _search(\@BLOCKS, 0, $#BLOCKS, $code);
697 return $result if defined $result;
700 elsif (exists $BLOCKS{$arg}) {
701 return _dclone $BLOCKS{$arg};
705 =head2 B<charscript()>
707 use Unicode::UCD 'charscript';
709 my $charscript = charscript(0x41);
710 my $charscript = charscript(1234);
711 my $charscript = charscript("U+263a");
713 my $range = charscript('Thai');
715 With a L</code point argument>, C<charscript()> returns the I<script> the
716 code point belongs to, e.g., C<Latin>, C<Greek>, C<Han>.
717 If the code point is unassigned or the Unicode version being used is so early
718 that it doesn't have scripts, this function returns C<"Unknown">.
720 If supplied with an argument that can't be a code point, charscript() tries
721 to do the opposite and interpret the argument as a script name. The
722 return value is a I<range set>: an anonymous list of lists that contain
723 I<start-of-range>, I<end-of-range> code point pairs. You can test whether a
724 code point is in a range set using the L</charinrange()> function.
725 (To be precise, each I<range set> contains a third array element,
726 after the range boundary ones: the script name.)
728 If the C<charscript()> argument is not a known script, C<undef> is returned.
730 See also L</Blocks versus Scripts>.
739 UnicodeVersion() unless defined $v_unicode_version;
740 if ($v_unicode_version lt v3.1.0) {
741 push @SCRIPTS, [ 0, 0x10FFFF, 'Unknown' ];
744 @SCRIPTS =_read_table("To/Sc.pl");
747 foreach my $entry (@SCRIPTS) {
748 $entry->[2] =~ s/(_\w)/\L$1/g; # Preserve old-style casing
749 push @{$SCRIPTS{$entry->[2]}}, $entry;
756 _charscripts() unless @SCRIPTS;
758 my $code = _getcode($arg);
761 my $result = _search(\@SCRIPTS, 0, $#SCRIPTS, $code);
762 return $result if defined $result;
763 return $utf8::SwashInfo{'ToSc'}{'missing'};
764 } elsif (exists $SCRIPTS{$arg}) {
765 return _dclone $SCRIPTS{$arg};
771 =head2 B<charblocks()>
773 use Unicode::UCD 'charblocks';
775 my $charblocks = charblocks();
777 C<charblocks()> returns a reference to a hash with the known block names
778 as the keys, and the code point ranges (see L</charblock()>) as the values.
780 The names are in the old-style (see L</Old-style versus new-style block
783 L<prop_invmap("block")|/prop_invmap()> can be used to get this same data in a
784 different type of data structure.
786 See also L</Blocks versus Scripts>.
791 _charblocks() unless %BLOCKS;
792 return _dclone \%BLOCKS;
795 =head2 B<charscripts()>
797 use Unicode::UCD 'charscripts';
799 my $charscripts = charscripts();
801 C<charscripts()> returns a reference to a hash with the known script
802 names as the keys, and the code point ranges (see L</charscript()>) as
805 L<prop_invmap("script")|/prop_invmap()> can be used to get this same data in a
806 different type of data structure.
808 See also L</Blocks versus Scripts>.
813 _charscripts() unless %SCRIPTS;
814 return _dclone \%SCRIPTS;
817 =head2 B<charinrange()>
819 In addition to using the C<\p{Blk=...}> and C<\P{Blk=...}> constructs, you
820 can also test whether a code point is in the I<range> as returned by
821 L</charblock()> and L</charscript()> or as the values of the hash returned
822 by L</charblocks()> and L</charscripts()> by using C<charinrange()>:
824 use Unicode::UCD qw(charscript charinrange);
826 $range = charscript('Hiragana');
827 print "looks like hiragana\n" if charinrange($range, $codepoint);
831 my %GENERAL_CATEGORIES =
834 'LC' => 'CasedLetter',
835 'Lu' => 'UppercaseLetter',
836 'Ll' => 'LowercaseLetter',
837 'Lt' => 'TitlecaseLetter',
838 'Lm' => 'ModifierLetter',
839 'Lo' => 'OtherLetter',
841 'Mn' => 'NonspacingMark',
842 'Mc' => 'SpacingMark',
843 'Me' => 'EnclosingMark',
845 'Nd' => 'DecimalNumber',
846 'Nl' => 'LetterNumber',
847 'No' => 'OtherNumber',
848 'P' => 'Punctuation',
849 'Pc' => 'ConnectorPunctuation',
850 'Pd' => 'DashPunctuation',
851 'Ps' => 'OpenPunctuation',
852 'Pe' => 'ClosePunctuation',
853 'Pi' => 'InitialPunctuation',
854 'Pf' => 'FinalPunctuation',
855 'Po' => 'OtherPunctuation',
857 'Sm' => 'MathSymbol',
858 'Sc' => 'CurrencySymbol',
859 'Sk' => 'ModifierSymbol',
860 'So' => 'OtherSymbol',
862 'Zs' => 'SpaceSeparator',
863 'Zl' => 'LineSeparator',
864 'Zp' => 'ParagraphSeparator',
869 'Co' => 'PrivateUse',
870 'Cn' => 'Unassigned',
873 sub general_categories {
874 return _dclone \%GENERAL_CATEGORIES;
877 =head2 B<general_categories()>
879 use Unicode::UCD 'general_categories';
881 my $categories = general_categories();
883 This returns a reference to a hash which has short
884 general category names (such as C<Lu>, C<Nd>, C<Zs>, C<S>) as keys and long
885 names (such as C<UppercaseLetter>, C<DecimalNumber>, C<SpaceSeparator>,
886 C<Symbol>) as values. The hash is reversible in case you need to go
887 from the long names to the short names. The general category is the
889 L</charinfo()> under the C<category> key.
891 The L</prop_value_aliases()> function can be used to get all the synonyms of
898 'L' => 'Left-to-Right',
899 'LRE' => 'Left-to-Right Embedding',
900 'LRO' => 'Left-to-Right Override',
901 'R' => 'Right-to-Left',
902 'AL' => 'Right-to-Left Arabic',
903 'RLE' => 'Right-to-Left Embedding',
904 'RLO' => 'Right-to-Left Override',
905 'PDF' => 'Pop Directional Format',
906 'EN' => 'European Number',
907 'ES' => 'European Number Separator',
908 'ET' => 'European Number Terminator',
909 'AN' => 'Arabic Number',
910 'CS' => 'Common Number Separator',
911 'NSM' => 'Non-Spacing Mark',
912 'BN' => 'Boundary Neutral',
913 'B' => 'Paragraph Separator',
914 'S' => 'Segment Separator',
915 'WS' => 'Whitespace',
916 'ON' => 'Other Neutrals',
919 =head2 B<bidi_types()>
921 use Unicode::UCD 'bidi_types';
923 my $categories = bidi_types();
925 This returns a reference to a hash which has the short
926 bidi (bidirectional) type names (such as C<L>, C<R>) as keys and long
927 names (such as C<Left-to-Right>, C<Right-to-Left>) as values. The
928 hash is reversible in case you need to go from the long names to the
929 short names. The bidi type is the one returned from
931 under the C<bidi> key. For the exact meaning of the various bidi classes
932 the Unicode TR9 is recommended reading:
933 L<http://www.unicode.org/reports/tr9/>
934 (as of Unicode 5.0.0)
936 The L</prop_value_aliases()> function can be used to get all the synonyms of
942 return _dclone \%BIDI_TYPES;
947 use Unicode::UCD 'compexcl';
949 my $compexcl = compexcl(0x09dc);
951 This routine returns C<undef> if the Unicode version being used is so early
952 that it doesn't have this property.
954 C<compexcl()> is included for backwards
955 compatibility, but as of Perl 5.12 and more modern Unicode versions, for
956 most purposes it is probably more convenient to use one of the following
959 my $compexcl = chr(0x09dc) =~ /\p{Comp_Ex};
960 my $compexcl = chr(0x09dc) =~ /\p{Full_Composition_Exclusion};
964 my $compexcl = chr(0x09dc) =~ /\p{CE};
965 my $compexcl = chr(0x09dc) =~ /\p{Composition_Exclusion};
967 The first two forms return B<true> if the L</code point argument> should not
968 be produced by composition normalization. For the final two forms to return
969 B<true>, it is additionally required that this fact not otherwise be
970 determinable from the Unicode data base.
972 This routine behaves identically to the final two forms. That is,
973 it does not return B<true> if the code point has a decomposition
974 consisting of another single code point, nor if its decomposition starts
975 with a code point whose combining class is non-zero. Code points that meet
976 either of these conditions should also not be produced by composition
977 normalization, which is probably why you should use the
978 C<Full_Composition_Exclusion> property instead, as shown above.
980 The routine returns B<false> otherwise.
986 my $code = _getcode($arg);
987 croak __PACKAGE__, "::compexcl: unknown code '$arg'"
988 unless defined $code;
990 UnicodeVersion() unless defined $v_unicode_version;
991 return if $v_unicode_version lt v3.0.0;
993 no warnings "non_unicode"; # So works on non-Unicode code points
994 return chr($code) =~ /\p{Composition_Exclusion}/;
999 use Unicode::UCD 'casefold';
1001 my $casefold = casefold(0xDF);
1002 if (defined $casefold) {
1003 my @full_fold_hex = split / /, $casefold->{'full'};
1004 my $full_fold_string =
1005 join "", map {chr(hex($_))} @full_fold_hex;
1006 my @turkic_fold_hex =
1007 split / /, ($casefold->{'turkic'} ne "")
1008 ? $casefold->{'turkic'}
1009 : $casefold->{'full'};
1010 my $turkic_fold_string =
1011 join "", map {chr(hex($_))} @turkic_fold_hex;
1013 if (defined $casefold && $casefold->{'simple'} ne "") {
1014 my $simple_fold_hex = $casefold->{'simple'};
1015 my $simple_fold_string = chr(hex($simple_fold_hex));
1018 This returns the (almost) locale-independent case folding of the
1019 character specified by the L</code point argument>. (Starting in Perl v5.16,
1020 the core function C<fc()> returns the C<full> mapping (described below)
1021 faster than this does, and for entire strings.)
1023 If there is no case folding for the input code point, C<undef> is returned.
1025 If there is a case folding for that code point, a reference to a hash
1026 with the following fields is returned:
1032 the input native L</code point argument> expressed in hexadecimal, with
1034 added if necessary to make it contain at least four hexdigits
1038 one or more codes (separated by spaces) that, taken in order, give the
1039 code points for the case folding for I<code>.
1040 Each has at least four hexdigits.
1044 is empty, or is exactly one code with at least four hexdigits which can be used
1045 as an alternative case folding when the calling program cannot cope with the
1046 fold being a sequence of multiple code points. If I<full> is just one code
1047 point, then I<simple> equals I<full>. If there is no single code point folding
1048 defined for I<code>, then I<simple> is the empty string. Otherwise, it is an
1049 inferior, but still better-than-nothing alternative folding to I<full>.
1053 is the same as I<simple> if I<simple> is not empty, and it is the same as I<full>
1054 otherwise. It can be considered to be the simplest possible folding for
1055 I<code>. It is defined primarily for backwards compatibility.
1059 is C<C> (for C<common>) if the best possible fold is a single code point
1060 (I<simple> equals I<full> equals I<mapping>). It is C<S> if there are distinct
1061 folds, I<simple> and I<full> (I<mapping> equals I<simple>). And it is C<F> if
1062 there is only a I<full> fold (I<mapping> equals I<full>; I<simple> is empty).
1064 describes the contents of I<mapping>. It is defined primarily for backwards
1067 For Unicode versions between 3.1 and 3.1.1 inclusive, I<status> can also be
1068 C<I> which is the same as C<C> but is a special case for dotted uppercase I and
1069 dotless lowercase i:
1073 =item Z<>B<*> If you use this C<I> mapping
1075 the result is case-insensitive,
1076 but dotless and dotted I's are not distinguished
1078 =item Z<>B<*> If you exclude this C<I> mapping
1080 the result is not fully case-insensitive, but
1081 dotless and dotted I's are distinguished
1087 contains any special folding for Turkic languages. For versions of Unicode
1088 starting with 3.2, this field is empty unless I<code> has a different folding
1089 in Turkic languages, in which case it is one or more codes (separated by
1090 spaces) that, taken in order, give the code points for the case folding for
1091 I<code> in those languages.
1092 Each code has at least four hexdigits.
1093 Note that this folding does not maintain canonical equivalence without
1094 additional processing.
1096 For Unicode versions between 3.1 and 3.1.1 inclusive, this field is empty unless
1098 special folding for Turkic languages, in which case I<status> is C<I>, and
1099 I<mapping>, I<full>, I<simple>, and I<turkic> are all equal.
1103 Programs that want complete generality and the best folding results should use
1104 the folding contained in the I<full> field. But note that the fold for some
1105 code points will be a sequence of multiple code points.
1107 Programs that can't cope with the fold mapping being multiple code points can
1108 use the folding contained in the I<simple> field, with the loss of some
1109 generality. In Unicode 5.1, about 7% of the defined foldings have no single
1112 The I<mapping> and I<status> fields are provided for backwards compatibility for
1113 existing programs. They contain the same values as in previous versions of
1116 Locale is not completely independent. The I<turkic> field contains results to
1117 use when the locale is a Turkic language.
1119 For more information about case mappings see
1120 L<http://www.unicode.org/unicode/reports/tr21>
1127 unless (%CASEFOLD) { # Populate the hash
1128 my ($full_invlist_ref, $full_invmap_ref, undef, $default)
1129 = prop_invmap('Case_Folding');
1131 # Use the recipe given in the prop_invmap() pod to convert the
1132 # inversion map into the hash.
1133 for my $i (0 .. @$full_invlist_ref - 1 - 1) {
1134 next if $full_invmap_ref->[$i] == $default;
1136 for my $j ($full_invlist_ref->[$i] .. $full_invlist_ref->[$i+1] -1) {
1138 if (! ref $full_invmap_ref->[$i]) {
1140 # This is a single character mapping
1141 $CASEFOLD{$j}{'status'} = 'C';
1142 $CASEFOLD{$j}{'simple'}
1143 = $CASEFOLD{$j}{'full'}
1144 = $CASEFOLD{$j}{'mapping'}
1145 = sprintf("%04X", $full_invmap_ref->[$i] + $adjust);
1146 $CASEFOLD{$j}{'code'} = sprintf("%04X", $j);
1147 $CASEFOLD{$j}{'turkic'} = "";
1149 else { # prop_invmap ensures that $adjust is 0 for a ref
1150 $CASEFOLD{$j}{'status'} = 'F';
1151 $CASEFOLD{$j}{'full'}
1152 = $CASEFOLD{$j}{'mapping'}
1153 = join " ", map { sprintf "%04X", $_ }
1154 @{$full_invmap_ref->[$i]};
1155 $CASEFOLD{$j}{'simple'} = "";
1156 $CASEFOLD{$j}{'code'} = sprintf("%04X", $j);
1157 $CASEFOLD{$j}{'turkic'} = "";
1162 # We have filled in the full mappings above, assuming there were no
1163 # simple ones for the ones with multi-character maps. Now, we find
1164 # and fix the cases where that assumption was false.
1165 (my ($simple_invlist_ref, $simple_invmap_ref, undef), $default)
1166 = prop_invmap('Simple_Case_Folding');
1167 for my $i (0 .. @$simple_invlist_ref - 1 - 1) {
1168 next if $simple_invmap_ref->[$i] == $default;
1170 for my $j ($simple_invlist_ref->[$i]
1171 .. $simple_invlist_ref->[$i+1] -1)
1174 next if $CASEFOLD{$j}{'status'} eq 'C';
1175 $CASEFOLD{$j}{'status'} = 'S';
1176 $CASEFOLD{$j}{'simple'}
1177 = $CASEFOLD{$j}{'mapping'}
1178 = sprintf("%04X", $simple_invmap_ref->[$i] + $adjust);
1179 $CASEFOLD{$j}{'code'} = sprintf("%04X", $j);
1180 $CASEFOLD{$j}{'turkic'} = "";
1184 # We hard-code in the turkish rules
1185 UnicodeVersion() unless defined $v_unicode_version;
1186 if ($v_unicode_version ge v3.2.0) {
1188 # These two code points should already have regular entries, so
1189 # just fill in the turkish fields
1190 $CASEFOLD{ord('I')}{'turkic'} = '0131';
1191 $CASEFOLD{0x130}{'turkic'} = sprintf "%04X", ord('i');
1193 elsif ($v_unicode_version ge v3.1.0) {
1195 # These two code points don't have entries otherwise.
1196 $CASEFOLD{0x130}{'code'} = '0130';
1197 $CASEFOLD{0x131}{'code'} = '0131';
1198 $CASEFOLD{0x130}{'status'} = $CASEFOLD{0x131}{'status'} = 'I';
1199 $CASEFOLD{0x130}{'turkic'}
1200 = $CASEFOLD{0x130}{'mapping'}
1201 = $CASEFOLD{0x130}{'full'}
1202 = $CASEFOLD{0x130}{'simple'}
1203 = $CASEFOLD{0x131}{'turkic'}
1204 = $CASEFOLD{0x131}{'mapping'}
1205 = $CASEFOLD{0x131}{'full'}
1206 = $CASEFOLD{0x131}{'simple'}
1207 = sprintf "%04X", ord('i');
1214 my $code = _getcode($arg);
1215 croak __PACKAGE__, "::casefold: unknown code '$arg'"
1216 unless defined $code;
1218 _casefold() unless %CASEFOLD;
1220 return $CASEFOLD{$code};
1223 =head2 B<all_casefolds()>
1226 use Unicode::UCD 'all_casefolds';
1228 my $all_folds_ref = all_casefolds();
1229 foreach my $char_with_casefold (sort { $a <=> $b }
1230 keys %$all_folds_ref)
1232 printf "%04X:", $char_with_casefold;
1233 my $casefold = $all_folds_ref->{$char_with_casefold};
1235 # Get folds for $char_with_casefold
1237 my @full_fold_hex = split / /, $casefold->{'full'};
1238 my $full_fold_string =
1239 join "", map {chr(hex($_))} @full_fold_hex;
1240 print " full=", join " ", @full_fold_hex;
1241 my @turkic_fold_hex =
1242 split / /, ($casefold->{'turkic'} ne "")
1243 ? $casefold->{'turkic'}
1244 : $casefold->{'full'};
1245 my $turkic_fold_string =
1246 join "", map {chr(hex($_))} @turkic_fold_hex;
1247 print "; turkic=", join " ", @turkic_fold_hex;
1248 if (defined $casefold && $casefold->{'simple'} ne "") {
1249 my $simple_fold_hex = $casefold->{'simple'};
1250 my $simple_fold_string = chr(hex($simple_fold_hex));
1251 print "; simple=$simple_fold_hex";
1256 This returns all the case foldings in the current version of Unicode in the
1257 form of a reference to a hash. Each key to the hash is the decimal
1258 representation of a Unicode character that has a casefold to other than
1259 itself. The casefold of a semi-colon is itself, so it isn't in the hash;
1260 likewise for a lowercase "a", but there is an entry for a capital "A". The
1261 hash value for each key is another hash, identical to what is returned by
1262 L</casefold()> if called with that code point as its argument. So the value
1263 C<< all_casefolds()->{ord("A")}' >> is equivalent to C<casefold(ord("A"))>;
1267 sub all_casefolds () {
1268 _casefold() unless %CASEFOLD;
1269 return _dclone \%CASEFOLD;
1272 =head2 B<casespec()>
1274 use Unicode::UCD 'casespec';
1276 my $casespec = casespec(0xFB00);
1278 This returns the potentially locale-dependent case mappings of the L</code point
1279 argument>. The mappings may be longer than a single code point (which the basic
1280 Unicode case mappings as returned by L</charinfo()> never are).
1282 If there are no case mappings for the L</code point argument>, or if all three
1283 possible mappings (I<lower>, I<title> and I<upper>) result in single code
1284 points and are locale independent and unconditional, C<undef> is returned
1285 (which means that the case mappings, if any, for the code point are those
1286 returned by L</charinfo()>).
1288 Otherwise, a reference to a hash giving the mappings (or a reference to a hash
1289 of such hashes, explained below) is returned with the following keys and their
1292 The keys in the bottom layer hash with the meanings of their values are:
1298 the input native L</code point argument> expressed in hexadecimal, with
1300 added if necessary to make it contain at least four hexdigits
1304 one or more codes (separated by spaces) that, taken in order, give the
1305 code points for the lower case of I<code>.
1306 Each has at least four hexdigits.
1310 one or more codes (separated by spaces) that, taken in order, give the
1311 code points for the title case of I<code>.
1312 Each has at least four hexdigits.
1316 one or more codes (separated by spaces) that, taken in order, give the
1317 code points for the upper case of I<code>.
1318 Each has at least four hexdigits.
1322 the conditions for the mappings to be valid.
1323 If C<undef>, the mappings are always valid.
1324 When defined, this field is a list of conditions,
1325 all of which must be true for the mappings to be valid.
1326 The list consists of one or more
1327 I<locales> (see below)
1328 and/or I<contexts> (explained in the next paragraph),
1329 separated by spaces.
1330 (Other than as used to separate elements, spaces are to be ignored.)
1331 Case distinctions in the condition list are not significant.
1332 Conditions preceded by "NON_" represent the negation of the condition.
1334 A I<context> is one of those defined in the Unicode standard.
1335 For Unicode 5.1, they are defined in Section 3.13 C<Default Case Operations>
1337 L<http://www.unicode.org/versions/Unicode5.1.0/>.
1338 These are for context-sensitive casing.
1342 The hash described above is returned for locale-independent casing, where
1343 at least one of the mappings has length longer than one. If C<undef> is
1344 returned, the code point may have mappings, but if so, all are length one,
1345 and are returned by L</charinfo()>.
1346 Note that when this function does return a value, it will be for the complete
1347 set of mappings for a code point, even those whose length is one.
1349 If there are additional casing rules that apply only in certain locales,
1350 an additional key for each will be defined in the returned hash. Each such key
1351 will be its locale name, defined as a 2-letter ISO 3166 country code, possibly
1352 followed by a "_" and a 2-letter ISO language code (possibly followed by a "_"
1353 and a variant code). You can find the lists of all possible locales, see
1354 L<Locale::Country> and L<Locale::Language>.
1355 (In Unicode 6.0, the only locales returned by this function
1356 are C<lt>, C<tr>, and C<az>.)
1358 Each locale key is a reference to a hash that has the form above, and gives
1359 the casing rules for that particular locale, which take precedence over the
1360 locale-independent ones when in that locale.
1362 If the only casing for a code point is locale-dependent, then the returned
1363 hash will not have any of the base keys, like C<code>, C<upper>, etc., but
1364 will contain only locale keys.
1366 For more information about case mappings see
1367 L<http://www.unicode.org/unicode/reports/tr21/>
1374 unless (%CASESPEC) {
1375 UnicodeVersion() unless defined $v_unicode_version;
1376 if ($v_unicode_version lt v2.1.8) {
1379 elsif (openunicode(\$CASESPECFH, "SpecialCasing.txt")) {
1382 while (<$CASESPECFH>) {
1383 if (/^([0-9A-F]+); ([0-9A-F]+(?: [0-9A-F]+)*)?; ([0-9A-F]+(?: [0-9A-F]+)*)?; ([0-9A-F]+(?: [0-9A-F]+)*)?; (\w+(?: \w+)*)?/) {
1385 my ($hexcode, $lower, $title, $upper, $condition) =
1386 ($1, $2, $3, $4, $5);
1387 if (! IS_ASCII_PLATFORM) { # Remap entry to native
1388 foreach my $var_ref (\$hexcode,
1393 next unless defined $$var_ref;
1394 $$var_ref = join " ",
1395 map { sprintf("%04X",
1396 utf8::unicode_to_native(hex $_)) }
1397 split " ", $$var_ref;
1401 my $code = hex($hexcode);
1403 # In 2.1.8, there were duplicate entries; ignore all but
1404 # the first one -- there were no conditions in the file
1406 if (exists $CASESPEC{$code} && $v_unicode_version ne v2.1.8)
1408 if (exists $CASESPEC{$code}->{code}) {
1413 @{$CASESPEC{$code}}{qw(lower
1417 if (defined $oldcondition) {
1419 ($oldcondition =~ /^([a-z][a-z](?:_\S+)?)/);
1420 delete $CASESPEC{$code};
1421 $CASESPEC{$code}->{$oldlocale} =
1426 condition => $oldcondition };
1430 ($condition =~ /^([a-z][a-z](?:_\S+)?)/);
1431 $CASESPEC{$code}->{$locale} =
1436 condition => $condition };
1443 condition => $condition };
1454 my $code = _getcode($arg);
1455 croak __PACKAGE__, "::casespec: unknown code '$arg'"
1456 unless defined $code;
1458 _casespec() unless %CASESPEC;
1460 return ref $CASESPEC{$code} ? _dclone $CASESPEC{$code} : $CASESPEC{$code};
1463 =head2 B<namedseq()>
1465 use Unicode::UCD 'namedseq';
1467 my $namedseq = namedseq("KATAKANA LETTER AINU P");
1468 my @namedseq = namedseq("KATAKANA LETTER AINU P");
1469 my %namedseq = namedseq();
1471 If used with a single argument in a scalar context, returns the string
1472 consisting of the code points of the named sequence, or C<undef> if no
1473 named sequence by that name exists. If used with a single argument in
1474 a list context, it returns the list of the ordinals of the code points.
1477 arguments in a list context, it returns a hash with the names of all the
1478 named sequences as the keys and their sequences as strings as
1479 the values. Otherwise, it returns C<undef> or an empty list depending
1482 This function only operates on officially approved (not provisional) named
1485 Note that as of Perl 5.14, C<\N{KATAKANA LETTER AINU P}> will insert the named
1486 sequence into double-quoted strings, and C<charnames::string_vianame("KATAKANA
1487 LETTER AINU P")> will return the same string this function does, but will also
1488 operate on character names that aren't named sequences, without you having to
1489 know which are which. See L<charnames>.
1496 unless (%NAMEDSEQ) {
1497 if (openunicode(\$NAMEDSEQFH, "Name.pl")) {
1500 while (<$NAMEDSEQFH>) {
1501 if (/^ [0-9A-F]+ \ /x) {
1503 my ($sequence, $name) = split /\t/;
1504 my @s = map { chr(hex($_)) } split(' ', $sequence);
1505 $NAMEDSEQ{$name} = join("", @s);
1515 # Use charnames::string_vianame() which now returns this information,
1516 # unless the caller wants the hash returned, in which case we read it in,
1517 # and thereafter use it instead of calling charnames, as it is faster.
1519 my $wantarray = wantarray();
1520 if (defined $wantarray) {
1523 _namedseq() unless %NAMEDSEQ;
1528 $s = $NAMEDSEQ{ $_[0] };
1531 $s = charnames::string_vianame($_[0]);
1533 return defined $s ? map { ord($_) } split('', $s) : ();
1536 return $NAMEDSEQ{ $_[0] } if %NAMEDSEQ;
1537 return charnames::string_vianame($_[0]);
1546 my @numbers = _read_table("To/Nv.pl");
1547 foreach my $entry (@numbers) {
1548 my ($start, $end, $value) = @$entry;
1550 # If value contains a slash, convert to decimal, add a reverse hash
1552 if ((my @rational = split /\//, $value) == 2) {
1553 my $real = $rational[0] / $rational[1];
1554 $real_to_rational{$real} = $value;
1557 # Should only be single element, but just in case...
1558 for my $i ($start .. $end) {
1559 $NUMERIC{$i} = $value;
1563 # The values require adjusting, as is in 'a' format
1564 for my $i ($start .. $end) {
1565 $NUMERIC{$i} = $value + $i - $start;
1570 # Decided unsafe to use these that aren't officially part of the Unicode
1573 #my $pi = acos(-1.0);
1574 #$NUMERIC{0x03C0} = $pi;
1576 # Euler's constant, not to be confused with Euler's number
1577 #$NUMERIC{0x2107} = 0.57721566490153286060651209008240243104215933593992;
1580 #$NUMERIC{0x212F} = 2.7182818284590452353602874713526624977572;
1589 use Unicode::UCD 'num';
1591 my $val = num("123");
1592 my $one_quarter = num("\N{VULGAR FRACTION 1/4}");
1594 C<num()> returns the numeric value of the input Unicode string; or C<undef> if it
1595 doesn't think the entire string has a completely valid, safe numeric value.
1597 If the string is just one character in length, the Unicode numeric value
1598 is returned if it has one, or C<undef> otherwise. Note that this need
1599 not be a whole number. C<num("\N{TIBETAN DIGIT HALF ZERO}")>, for
1600 example returns -0.5.
1604 #A few characters to which Unicode doesn't officially
1605 #assign a numeric value are considered numeric by C<num>.
1608 # EULER CONSTANT 0.5772... (this is NOT Euler's number)
1609 # SCRIPT SMALL E 2.71828... (this IS Euler's number)
1610 # GREEK SMALL LETTER PI 3.14159...
1614 If the string is more than one character, C<undef> is returned unless
1615 all its characters are decimal digits (that is, they would match C<\d+>),
1616 from the same script. For example if you have an ASCII '0' and a Bengali
1617 '3', mixed together, they aren't considered a valid number, and C<undef>
1618 is returned. A further restriction is that the digits all have to be of
1619 the same form. A half-width digit mixed with a full-width one will
1620 return C<undef>. The Arabic script has two sets of digits; C<num> will
1621 return C<undef> unless all the digits in the string come from the same
1624 C<num> errs on the side of safety, and there may be valid strings of
1625 decimal digits that it doesn't recognize. Note that Unicode defines
1626 a number of "digit" characters that aren't "decimal digit" characters.
1627 "Decimal digits" have the property that they have a positional value, i.e.,
1628 there is a units position, a 10's position, a 100's, etc, AND they are
1629 arranged in Unicode in blocks of 10 contiguous code points. The Chinese
1630 digits, for example, are not in such a contiguous block, and so Unicode
1631 doesn't view them as decimal digits, but merely digits, and so C<\d> will not
1632 match them. A single-character string containing one of these digits will
1633 have its decimal value returned by C<num>, but any longer string containing
1634 only these digits will return C<undef>.
1636 Strings of multiple sub- and superscripts are not recognized as numbers. You
1637 can use either of the compatibility decompositions in Unicode::Normalize to
1638 change these into digits, and then call C<num> on the result.
1642 # To handle sub, superscripts, this could if called in list context,
1643 # consider those, and return the <decomposition> type in the second
1649 _numeric unless %NUMERIC;
1651 my $length = length($string);
1652 return $NUMERIC{ord($string)} if $length == 1;
1653 return if $string =~ /\D/;
1654 my $first_ord = ord(substr($string, 0, 1));
1655 my $value = $NUMERIC{$first_ord};
1657 # To be a valid decimal number, it should be in a block of 10 consecutive
1658 # characters, whose values are 0, 1, 2, ... 9. Therefore this digit's
1659 # value is its offset in that block from the character that means zero.
1660 my $zero_ord = $first_ord - $value;
1662 # Unicode 6.0 instituted the rule that only digits in a consecutive
1663 # block of 10 would be considered decimal digits. If this is an earlier
1664 # release, we verify that this first character is a member of such a
1665 # block. That is, that the block of characters surrounding this one
1666 # consists of all \d characters whose numeric values are the expected
1668 UnicodeVersion() unless defined $v_unicode_version;
1669 if ($v_unicode_version lt v6.0.0) {
1670 for my $i (0 .. 9) {
1671 my $ord = $zero_ord + $i;
1672 return unless chr($ord) =~ /\d/;
1673 my $numeric = $NUMERIC{$ord};
1674 return unless defined $numeric;
1675 return unless $numeric == $i;
1679 for my $i (1 .. $length -1) {
1681 # Here we know either by verifying, or by fact of the first character
1682 # being a \d in Unicode 6.0 or later, that any character between the
1683 # character that means 0, and 9 positions above it must be \d, and
1684 # must have its value correspond to its offset from the zero. Any
1685 # characters outside these 10 do not form a legal number for this
1687 my $ord = ord(substr($string, $i, 1));
1688 my $digit = $ord - $zero_ord;
1689 return unless $digit >= 0 && $digit <= 9;
1690 $value = $value * 10 + $digit;
1698 =head2 B<prop_aliases()>
1700 use Unicode::UCD 'prop_aliases';
1702 my ($short_name, $full_name, @other_names) = prop_aliases("space");
1703 my $same_full_name = prop_aliases("Space"); # Scalar context
1704 my ($same_short_name) = prop_aliases("Space"); # gets 0th element
1705 print "The full name is $full_name\n";
1706 print "The short name is $short_name\n";
1707 print "The other aliases are: ", join(", ", @other_names), "\n";
1710 The full name is White_Space
1711 The short name is WSpace
1712 The other aliases are: Space
1714 Most Unicode properties have several synonymous names. Typically, there is at
1715 least a short name, convenient to type, and a long name that more fully
1716 describes the property, and hence is more easily understood.
1718 If you know one name for a Unicode property, you can use C<prop_aliases> to find
1719 either the long name (when called in scalar context), or a list of all of the
1720 names, somewhat ordered so that the short name is in the 0th element, the long
1721 name in the next element, and any other synonyms are in the remaining
1722 elements, in no particular order.
1724 The long name is returned in a form nicely capitalized, suitable for printing.
1726 The input parameter name is loosely matched, which means that white space,
1727 hyphens, and underscores are ignored (except for the trailing underscore in
1728 the old_form grandfathered-in C<"L_">, which is better written as C<"LC">, and
1729 both of which mean C<General_Category=Cased Letter>).
1731 If the name is unknown, C<undef> is returned (or an empty list in list
1732 context). Note that Perl typically recognizes property names in regular
1733 expressions with an optional C<"Is_>" (with or without the underscore)
1734 prefixed to them, such as C<\p{isgc=punct}>. This function does not recognize
1735 those in the input, returning C<undef>. Nor are they included in the output
1736 as possible synonyms.
1738 C<prop_aliases> does know about the Perl extensions to Unicode properties,
1739 such as C<Any> and C<XPosixAlpha>, and the single form equivalents to Unicode
1740 properties such as C<XDigit>, C<Greek>, C<In_Greek>, and C<Is_Greek>. The
1741 final example demonstrates that the C<"Is_"> prefix is recognized for these
1742 extensions; it is needed to resolve ambiguities. For example,
1743 C<prop_aliases('lc')> returns the list C<(lc, Lowercase_Mapping)>, but
1744 C<prop_aliases('islc')> returns C<(Is_LC, Cased_Letter)>. This is
1745 because C<islc> is a Perl extension which is short for
1746 C<General_Category=Cased Letter>. The lists returned for the Perl extensions
1747 will not include the C<"Is_"> prefix (whether or not the input had it) unless
1748 needed to resolve ambiguities, as shown in the C<"islc"> example, where the
1749 returned list had one element containing C<"Is_">, and the other without.
1751 It is also possible for the reverse to happen: C<prop_aliases('isc')> returns
1752 the list C<(isc, ISO_Comment)>; whereas C<prop_aliases('c')> returns
1753 C<(C, Other)> (the latter being a Perl extension meaning
1754 C<General_Category=Other>.
1755 L<perluniprops/Properties accessible through Unicode::UCD> lists the available
1756 forms, including which ones are discouraged from use.
1758 Those discouraged forms are accepted as input to C<prop_aliases>, but are not
1759 returned in the lists. C<prop_aliases('isL&')> and C<prop_aliases('isL_')>,
1760 which are old synonyms for C<"Is_LC"> and should not be used in new code, are
1761 examples of this. These both return C<(Is_LC, Cased_Letter)>. Thus this
1762 function allows you to take a discouraged form, and find its acceptable
1763 alternatives. The same goes with single-form Block property equivalences.
1764 Only the forms that begin with C<"In_"> are not discouraged; if you pass
1765 C<prop_aliases> a discouraged form, you will get back the equivalent ones that
1766 begin with C<"In_">. It will otherwise look like a new-style block name (see.
1767 L</Old-style versus new-style block names>).
1769 C<prop_aliases> does not know about any user-defined properties, and will
1770 return C<undef> if called with one of those. Likewise for Perl internal
1771 properties, with the exception of "Perl_Decimal_Digit" which it does know
1772 about (and which is documented below in L</prop_invmap()>).
1776 # It may be that there are use cases where the discouraged forms should be
1777 # returned. If that comes up, an optional boolean second parameter to the
1778 # function could be created, for example.
1780 # These are created by mktables for this routine and stored in unicore/UCD.pl
1781 # where their structures are described.
1782 our %string_property_loose_to_name;
1783 our %ambiguous_names;
1784 our %loose_perlprop_to_name;
1787 sub prop_aliases ($) {
1789 return unless defined $prop;
1791 require "unicore/UCD.pl";
1792 require "unicore/Heavy.pl";
1793 require "utf8_heavy.pl";
1795 # The property name may be loosely or strictly matched; we don't know yet.
1796 # But both types use lower-case.
1799 # It is loosely matched if its lower case isn't known to be strict.
1801 if (! exists $utf8::stricter_to_file_of{$prop}) {
1802 my $loose = utf8::_loose_name($prop);
1804 # There is a hash that converts from any loose name to its standard
1805 # form, mapping all synonyms for a name to one name that can be used
1806 # as a key into another hash. The whole concept is for memory
1807 # savings, as the second hash doesn't have to have all the
1808 # combinations. Actually, there are two hashes that do the
1809 # converstion. One is used in utf8_heavy.pl (stored in Heavy.pl) for
1810 # looking up properties matchable in regexes. This function needs to
1811 # access string properties, which aren't available in regexes, so a
1812 # second conversion hash is made for them (stored in UCD.pl). Look in
1813 # the string one now, as the rest can have an optional 'is' prefix,
1814 # which these don't.
1815 if (exists $string_property_loose_to_name{$loose}) {
1817 # Convert to its standard loose name.
1818 $prop = $string_property_loose_to_name{$loose};
1821 my $retrying = 0; # bool. ? Has an initial 'is' been stripped
1823 if (exists $utf8::loose_property_name_of{$loose}
1825 || ! exists $ambiguous_names{$loose}))
1827 # Found an entry giving the standard form. We don't get here
1828 # (in the test above) when we've stripped off an
1829 # 'is' and the result is an ambiguous name. That is because
1830 # these are official Unicode properties (though Perl can have
1831 # an optional 'is' prefix meaning the official property), and
1832 # all ambiguous cases involve a Perl single-form extension
1833 # for the gc, script, or block properties, and the stripped
1834 # 'is' means that they mean one of those, and not one of
1836 $prop = $utf8::loose_property_name_of{$loose};
1838 elsif (exists $loose_perlprop_to_name{$loose}) {
1840 # This hash is specifically for this function to list Perl
1841 # extensions that aren't in the earlier hashes. If there is
1842 # only one element, the short and long names are identical.
1843 # Otherwise the form is already in the same form as
1844 # %prop_aliases, which is handled at the end of the function.
1845 $list_ref = $loose_perlprop_to_name{$loose};
1846 if (@$list_ref == 1) {
1847 my @list = ($list_ref->[0], $list_ref->[0]);
1851 elsif (! exists $utf8::loose_to_file_of{$loose}) {
1853 # loose_to_file_of is a complete list of loose names. If not
1854 # there, the input is unknown.
1857 elsif ($loose =~ / [:=] /x) {
1859 # Here we found the name but not its aliases, so it has to
1860 # exist. Exclude property-value combinations. (This shows up
1861 # for something like ccc=vr which matches loosely, but is a
1862 # synonym for ccc=9 which matches only strictly.
1867 # Here it has to exist, and isn't a property-value
1868 # combination. This means it must be one of the Perl
1869 # single-form extensions. First see if it is for a
1870 # property-value combination in one of the following
1873 foreach my $property ("gc", "script") {
1874 @list = prop_value_aliases($property, $loose);
1879 # Here, it is one of those property-value combination
1880 # single-form synonyms. There are ambiguities with some
1881 # of these. Check against the list for these, and adjust
1883 for my $i (0 .. @list -1) {
1884 if (exists $ambiguous_names
1885 {utf8::_loose_name(lc $list[$i])})
1887 # The ambiguity is resolved by toggling whether or
1888 # not it has an 'is' prefix
1889 $list[$i] =~ s/^Is_// or $list[$i] =~ s/^/Is_/;
1895 # Here, it wasn't one of the gc or script single-form
1896 # extensions. It could be a block property single-form
1897 # extension. An 'in' prefix definitely means that, and should
1898 # be looked up without the prefix. However, starting in
1899 # Unicode 6.1, we have to special case 'indic...', as there
1900 # is a property that begins with that name. We shouldn't
1901 # strip the 'in' from that. I'm (khw) generalizing this to
1902 # 'indic' instead of the single property, because I suspect
1903 # that others of this class may come along in the future.
1904 # However, this could backfire and a block created whose name
1905 # begins with 'dic...', and we would want to strip the 'in'.
1906 # At which point this would have to be tweaked.
1907 my $began_with_in = $loose =~ s/^in(?!dic)//;
1908 @list = prop_value_aliases("block", $loose);
1910 map { $_ =~ s/^/In_/ } @list;
1914 # Here still haven't found it. The last opportunity for it
1915 # being valid is only if it began with 'is'. We retry without
1916 # the 'is', setting a flag to that effect so that we don't
1917 # accept things that begin with 'isis...'
1918 if (! $retrying && ! $began_with_in && $loose =~ s/^is//) {
1923 # Here, didn't find it. Since it was in %loose_to_file_of, we
1924 # should have been able to find it.
1925 carp __PACKAGE__, "::prop_aliases: Unexpectedly could not find '$prop'. Send bug report to perlbug\@perl.org";
1932 # Here, we have set $prop to a standard form name of the input. Look
1933 # it up in the structure created by mktables for this purpose, which
1934 # contains both strict and loosely matched properties. Avoid
1936 $list_ref = $prop_aliases{$prop} if exists $prop_aliases{$prop};
1937 return unless $list_ref;
1940 # The full name is in element 1.
1941 return $list_ref->[1] unless wantarray;
1943 return @{_dclone $list_ref};
1948 =head2 B<prop_value_aliases()>
1950 use Unicode::UCD 'prop_value_aliases';
1952 my ($short_name, $full_name, @other_names)
1953 = prop_value_aliases("Gc", "Punct");
1954 my $same_full_name = prop_value_aliases("Gc", "P"); # Scalar cntxt
1955 my ($same_short_name) = prop_value_aliases("Gc", "P"); # gets 0th
1957 print "The full name is $full_name\n";
1958 print "The short name is $short_name\n";
1959 print "The other aliases are: ", join(", ", @other_names), "\n";
1962 The full name is Punctuation
1964 The other aliases are: Punct
1966 Some Unicode properties have a restricted set of legal values. For example,
1967 all binary properties are restricted to just C<true> or C<false>; and there
1968 are only a few dozen possible General Categories.
1970 For such properties, there are usually several synonyms for each possible
1971 value. For example, in binary properties, I<truth> can be represented by any of
1972 the strings "Y", "Yes", "T", or "True"; and the General Category
1973 "Punctuation" by that string, or "Punct", or simply "P".
1975 Like property names, there is typically at least a short name for each such
1976 property-value, and a long name. If you know any name of the property-value,
1977 you can use C<prop_value_aliases>() to get the long name (when called in
1978 scalar context), or a list of all the names, with the short name in the 0th
1979 element, the long name in the next element, and any other synonyms in the
1980 remaining elements, in no particular order, except that any all-numeric
1981 synonyms will be last.
1983 The long name is returned in a form nicely capitalized, suitable for printing.
1985 Case, white space, hyphens, and underscores are ignored in the input parameters
1986 (except for the trailing underscore in the old-form grandfathered-in general
1987 category property value C<"L_">, which is better written as C<"LC">).
1989 If either name is unknown, C<undef> is returned. Note that Perl typically
1990 recognizes property names in regular expressions with an optional C<"Is_>"
1991 (with or without the underscore) prefixed to them, such as C<\p{isgc=punct}>.
1992 This function does not recognize those in the property parameter, returning
1995 If called with a property that doesn't have synonyms for its values, it
1996 returns the input value, possibly normalized with capitalization and
1999 For the block property, new-style block names are returned (see
2000 L</Old-style versus new-style block names>).
2002 To find the synonyms for single-forms, such as C<\p{Any}>, use
2003 L</prop_aliases()> instead.
2005 C<prop_value_aliases> does not know about any user-defined properties, and
2006 will return C<undef> if called with one of those.
2010 # These are created by mktables for this routine and stored in unicore/UCD.pl
2011 # where their structures are described.
2012 our %loose_to_standard_value;
2013 our %prop_value_aliases;
2015 sub prop_value_aliases ($$) {
2016 my ($prop, $value) = @_;
2017 return unless defined $prop && defined $value;
2019 require "unicore/UCD.pl";
2020 require "utf8_heavy.pl";
2022 # Find the property name synonym that's used as the key in other hashes,
2023 # which is element 0 in the returned list.
2024 ($prop) = prop_aliases($prop);
2026 $prop = utf8::_loose_name(lc $prop);
2028 # Here is a legal property, but the hash below (created by mktables for
2029 # this purpose) only knows about the properties that have a very finite
2030 # number of potential values, that is not ones whose value could be
2031 # anything, like most (if not all) string properties. These don't have
2032 # synonyms anyway. Simply return the input. For example, there is no
2033 # synonym for ('Uppercase_Mapping', A').
2034 return $value if ! exists $prop_value_aliases{$prop};
2036 # The value name may be loosely or strictly matched; we don't know yet.
2037 # But both types use lower-case.
2040 # If the name isn't found under loose matching, it certainly won't be
2041 # found under strict
2042 my $loose_value = utf8::_loose_name($value);
2043 return unless exists $loose_to_standard_value{"$prop=$loose_value"};
2045 # Similarly if the combination under loose matching doesn't exist, it
2046 # won't exist under strict.
2047 my $standard_value = $loose_to_standard_value{"$prop=$loose_value"};
2048 return unless exists $prop_value_aliases{$prop}{$standard_value};
2050 # Here we did find a combination under loose matching rules. But it could
2051 # be that is a strict property match that shouldn't have matched.
2052 # %prop_value_aliases is set up so that the strict matches will appear as
2053 # if they were in loose form. Thus, if the non-loose version is legal,
2054 # we're ok, can skip the further check.
2055 if (! exists $utf8::stricter_to_file_of{"$prop=$value"}
2057 # We're also ok and skip the further check if value loosely matches.
2058 # mktables has verified that no strict name under loose rules maps to
2059 # an existing loose name. This code relies on the very limited
2060 # circumstances that strict names can be here. Strict name matching
2061 # happens under two conditions:
2062 # 1) when the name begins with an underscore. But this function
2063 # doesn't accept those, and %prop_value_aliases doesn't have
2065 # 2) When the values are numeric, in which case we need to look
2066 # further, but their squeezed-out loose values will be in
2067 # %stricter_to_file_of
2068 && exists $utf8::stricter_to_file_of{"$prop=$loose_value"})
2070 # The only thing that's legal loosely under strict is that can have an
2071 # underscore between digit pairs XXX
2072 while ($value =~ s/(\d)_(\d)/$1$2/g) {}
2073 return unless exists $utf8::stricter_to_file_of{"$prop=$value"};
2076 # Here, we know that the combination exists. Return it.
2077 my $list_ref = $prop_value_aliases{$prop}{$standard_value};
2078 if (@$list_ref > 1) {
2079 # The full name is in element 1.
2080 return $list_ref->[1] unless wantarray;
2082 return @{_dclone $list_ref};
2085 return $list_ref->[0] unless wantarray;
2087 # Only 1 element means that it repeats
2088 return ( $list_ref->[0], $list_ref->[0] );
2091 # All 1 bits is the largest possible UV.
2092 $Unicode::UCD::MAX_CP = ~0;
2096 =head2 B<prop_invlist()>
2098 C<prop_invlist> returns an inversion list (described below) that defines all the
2099 code points for the binary Unicode property (or "property=value" pair) given
2100 by the input parameter string:
2103 use Unicode::UCD 'prop_invlist';
2104 say join ", ", prop_invlist("Any");
2109 If the input is unknown C<undef> is returned in scalar context; an empty-list
2110 in list context. If the input is known, the number of elements in
2111 the list is returned if called in scalar context.
2113 L<perluniprops|perluniprops/Properties accessible through \p{} and \P{}> gives
2114 the list of properties that this function accepts, as well as all the possible
2115 forms for them (including with the optional "Is_" prefixes). (Except this
2116 function doesn't accept any Perl-internal properties, some of which are listed
2117 there.) This function uses the same loose or tighter matching rules for
2118 resolving the input property's name as is done for regular expressions. These
2119 are also specified in L<perluniprops|perluniprops/Properties accessible
2120 through \p{} and \P{}>. Examples of using the "property=value" form are:
2122 say join ", ", prop_invlist("Script=Shavian");
2127 say join ", ", prop_invlist("ASCII_Hex_Digit=No");
2130 0, 48, 58, 65, 71, 97, 103
2132 say join ", ", prop_invlist("ASCII_Hex_Digit=Yes");
2135 48, 58, 65, 71, 97, 103
2137 Inversion lists are a compact way of specifying Unicode property-value
2138 definitions. The 0th item in the list is the lowest code point that has the
2139 property-value. The next item (item [1]) is the lowest code point beyond that
2140 one that does NOT have the property-value. And the next item beyond that
2141 ([2]) is the lowest code point beyond that one that does have the
2142 property-value, and so on. Put another way, each element in the list gives
2143 the beginning of a range that has the property-value (for even numbered
2144 elements), or doesn't have the property-value (for odd numbered elements).
2145 The name for this data structure stems from the fact that each element in the
2146 list toggles (or inverts) whether the corresponding range is or isn't on the
2149 In the final example above, the first ASCII Hex digit is code point 48, the
2150 character "0", and all code points from it through 57 (a "9") are ASCII hex
2151 digits. Code points 58 through 64 aren't, but 65 (an "A") through 70 (an "F")
2152 are, as are 97 ("a") through 102 ("f"). 103 starts a range of code points
2153 that aren't ASCII hex digits. That range extends to infinity, which on your
2154 computer can be found in the variable C<$Unicode::UCD::MAX_CP>. (This
2155 variable is as close to infinity as Perl can get on your platform, and may be
2156 too high for some operations to work; you may wish to use a smaller number for
2159 Note that the inversion lists returned by this function can possibly include
2160 non-Unicode code points, that is anything above 0x10FFFF. Unicode properties
2161 are not defined on such code points. You might wish to change the output to
2162 not include these. Simply add 0x110000 at the end of the non-empty returned
2163 list if it isn't already that value; and pop that value if it is; like:
2165 my @list = prop_invlist("foo");
2167 if ($list[-1] == 0x110000) {
2168 pop @list; # Defeat the turning on for above Unicode
2171 push @list, 0x110000; # Turn off for above Unicode
2175 It is a simple matter to expand out an inversion list to a full list of all
2176 code points that have the property-value:
2178 my @invlist = prop_invlist($property_name);
2179 die "empty" unless @invlist;
2181 for (my $i = 0; $i < @invlist; $i += 2) {
2182 my $upper = ($i + 1) < @invlist
2183 ? $invlist[$i+1] - 1 # In range
2184 : $Unicode::UCD::MAX_CP; # To infinity. You may want
2185 # to stop much much earlier;
2186 # going this high may expose
2187 # perl deficiencies with very
2189 for my $j ($invlist[$i] .. $upper) {
2190 push @full_list, $j;
2194 C<prop_invlist> does not know about any user-defined nor Perl internal-only
2195 properties, and will return C<undef> if called with one of those.
2197 The L</search_invlist()> function is provided for finding a code point within
2202 # User-defined properties could be handled with some changes to utf8_heavy.pl;
2203 # and implementing here of dealing with EXTRAS. If done, consideration should
2204 # be given to the fact that the user subroutine could return different results
2205 # with each call; security issues need to be thought about.
2207 # These are created by mktables for this routine and stored in unicore/UCD.pl
2208 # where their structures are described.
2209 our %loose_defaults;
2210 our $MAX_UNICODE_CODEPOINT;
2212 sub prop_invlist ($;$) {
2215 # Undocumented way to get at Perl internal properties
2216 my $internal_ok = defined $_[1] && $_[1] eq '_perl_core_internal_ok';
2218 return if ! defined $prop;
2220 require "utf8_heavy.pl";
2222 # Warnings for these are only for regexes, so not applicable to us
2223 no warnings 'deprecated';
2225 # Get the swash definition of the property-value.
2226 my $swash = utf8::SWASHNEW(__PACKAGE__, $prop, undef, 1, 0);
2228 # Fail if not found, or isn't a boolean property-value, or is a
2229 # user-defined property, or is internal-only.
2232 || $swash->{'BITS'} != 1
2233 || $swash->{'USER_DEFINED'}
2234 || (! $internal_ok && $prop =~ /^\s*_/);
2236 if ($swash->{'EXTRAS'}) {
2237 carp __PACKAGE__, "::prop_invlist: swash returned for $prop unexpectedly has EXTRAS magic";
2240 if ($swash->{'SPECIALS'}) {
2241 carp __PACKAGE__, "::prop_invlist: swash returned for $prop unexpectedly has SPECIALS magic";
2247 if ($swash->{'LIST'} =~ /^V/) {
2249 # A 'V' as the first character marks the input as already an inversion
2250 # list, in which case, all we need to do is put the remaining lines
2252 @invlist = split "\n", $swash->{'LIST'} =~ s/ \s* (?: \# .* )? $ //xmgr;
2256 # The input lines look like:
2260 # Split into lines, stripped of trailing comments
2261 foreach my $range (split "\n",
2262 $swash->{'LIST'} =~ s/ \s* (?: \# .* )? $ //xmgr)
2264 # And find the beginning and end of the range on the line
2265 my ($hex_begin, $hex_end) = split "\t", $range;
2266 my $begin = hex $hex_begin;
2268 # If the new range merely extends the old, we remove the marker
2269 # created the last time through the loop for the old's end, which
2270 # causes the new one's end to be used instead.
2271 if (@invlist && $begin == $invlist[-1]) {
2275 # Add the beginning of the range
2276 push @invlist, $begin;
2279 if (defined $hex_end) { # The next item starts with the code point 1
2280 # beyond the end of the range.
2281 no warnings 'portable';
2282 my $end = hex $hex_end;
2283 last if $end == $Unicode::UCD::MAX_CP;
2284 push @invlist, $end + 1;
2286 else { # No end of range, is a single code point.
2287 push @invlist, $begin + 1;
2292 # Could need to be inverted: add or subtract a 0 at the beginning of the
2294 if ($swash->{'INVERT_IT'}) {
2295 if (@invlist && $invlist[0] == 0) {
2299 unshift @invlist, 0;
2308 =head2 B<prop_invmap()>
2310 use Unicode::UCD 'prop_invmap';
2311 my ($list_ref, $map_ref, $format, $default)
2312 = prop_invmap("General Category");
2314 C<prop_invmap> is used to get the complete mapping definition for a property,
2315 in the form of an inversion map. An inversion map consists of two parallel
2316 arrays. One is an ordered list of code points that mark range beginnings, and
2317 the other gives the value (or mapping) that all code points in the
2318 corresponding range have.
2320 C<prop_invmap> is called with the name of the desired property. The name is
2321 loosely matched, meaning that differences in case, white-space, hyphens, and
2322 underscores are not meaningful (except for the trailing underscore in the
2323 old-form grandfathered-in property C<"L_">, which is better written as C<"LC">,
2324 or even better, C<"Gc=LC">).
2326 Many Unicode properties have more than one name (or alias). C<prop_invmap>
2327 understands all of these, including Perl extensions to them. Ambiguities are
2328 resolved as described above for L</prop_aliases()>. The Perl internal
2329 property "Perl_Decimal_Digit, described below, is also accepted. An empty
2330 list is returned if the property name is unknown.
2331 See L<perluniprops/Properties accessible through Unicode::UCD> for the
2332 properties acceptable as inputs to this function.
2334 It is a fatal error to call this function except in list context.
2336 In addition to the two arrays that form the inversion map, C<prop_invmap>
2337 returns two other values; one is a scalar that gives some details as to the
2338 format of the entries of the map array; the other is a default value, useful
2339 in maps whose format name begins with the letter C<"a">, as described
2340 L<below in its subsection|/a>; and for specialized purposes, such as
2341 converting to another data structure, described at the end of this main
2344 This means that C<prop_invmap> returns a 4 element list. For example,
2346 my ($blocks_ranges_ref, $blocks_maps_ref, $format, $default)
2347 = prop_invmap("Block");
2349 In this call, the two arrays will be populated as shown below (for Unicode
2352 Index @blocks_ranges @blocks_maps
2353 0 0x0000 Basic Latin
2354 1 0x0080 Latin-1 Supplement
2355 2 0x0100 Latin Extended-A
2356 3 0x0180 Latin Extended-B
2357 4 0x0250 IPA Extensions
2358 5 0x02B0 Spacing Modifier Letters
2359 6 0x0300 Combining Diacritical Marks
2360 7 0x0370 Greek and Coptic
2363 233 0x2B820 No_Block
2364 234 0x2F800 CJK Compatibility Ideographs Supplement
2365 235 0x2FA20 No_Block
2367 237 0xE0080 No_Block
2368 238 0xE0100 Variation Selectors Supplement
2369 239 0xE01F0 No_Block
2370 240 0xF0000 Supplementary Private Use Area-A
2371 241 0x100000 Supplementary Private Use Area-B
2372 242 0x110000 No_Block
2374 The first line (with Index [0]) means that the value for code point 0 is "Basic
2375 Latin". The entry "0x0080" in the @blocks_ranges column in the second line
2376 means that the value from the first line, "Basic Latin", extends to all code
2377 points in the range from 0 up to but not including 0x0080, that is, through
2378 127. In other words, the code points from 0 to 127 are all in the "Basic
2379 Latin" block. Similarly, all code points in the range from 0x0080 up to (but
2380 not including) 0x0100 are in the block named "Latin-1 Supplement", etc.
2381 (Notice that the return is the old-style block names; see L</Old-style versus
2382 new-style block names>).
2384 The final line (with Index [242]) means that the value for all code points above
2385 the legal Unicode maximum code point have the value "No_Block", which is the
2386 term Unicode uses for a non-existing block.
2388 The arrays completely specify the mappings for all possible code points.
2389 The final element in an inversion map returned by this function will always be
2390 for the range that consists of all the code points that aren't legal Unicode,
2391 but that are expressible on the platform. (That is, it starts with code point
2392 0x110000, the first code point above the legal Unicode maximum, and extends to
2393 infinity.) The value for that range will be the same that any typical
2394 unassigned code point has for the specified property. (Certain unassigned
2395 code points are not "typical"; for example the non-character code points, or
2396 those in blocks that are to be written right-to-left. The above-Unicode
2397 range's value is not based on these atypical code points.) It could be argued
2398 that, instead of treating these as unassigned Unicode code points, the value
2399 for this range should be C<undef>. If you wish, you can change the returned
2402 The maps for almost all properties are simple scalars that should be
2404 These values are those given in the Unicode-supplied data files, which may be
2405 inconsistent as to capitalization and as to which synonym for a property-value
2406 is given. The results may be normalized by using the L</prop_value_aliases()>
2409 There are exceptions to the simple scalar maps. Some properties have some
2410 elements in their map list that are themselves lists of scalars; and some
2411 special strings are returned that are not to be interpreted as-is. Element
2412 [2] (placed into C<$format> in the example above) of the returned four element
2413 list tells you if the map has any of these special elements or not, as follows:
2419 means all the elements of the map array are simple scalars, with no special
2420 elements. Almost all properties are like this, like the C<block> example
2425 means that some of the map array elements have the form given by C<"s">, and
2426 the rest are lists of scalars. For example, here is a portion of the output
2427 of calling C<prop_invmap>() with the "Script Extensions" property:
2429 @scripts_ranges @scripts_maps
2432 0x0964 [ Bengali, Devanagari, Gurumukhi, Oriya ]
2436 Here, the code points 0x964 and 0x965 are both used in Bengali,
2437 Devanagari, Gurmukhi, and Oriya, but no other scripts.
2439 The Name_Alias property is also of this form. But each scalar consists of two
2440 components: 1) the name, and 2) the type of alias this is. They are
2441 separated by a colon and a space. In Unicode 6.1, there are several alias types:
2447 indicates that the name is a corrected form for the
2448 original name (which remains valid) for the same code point.
2452 adds a new name for a control character.
2456 is an alternate name for a character
2460 is a name for a character that has been documented but was never in any
2463 =item C<abbreviation>
2465 is a common abbreviation for a character
2469 The lists are ordered (roughly) so the most preferred names come before less
2474 @aliases_ranges @alias_maps
2476 0x009E [ 'PRIVACY MESSAGE: control', 'PM: abbreviation' ]
2477 0x009F [ 'APPLICATION PROGRAM COMMAND: control',
2480 0x00A0 'NBSP: abbreviation'
2482 0x00AD 'SHY: abbreviation'
2484 0x01A2 'LATIN CAPITAL LETTER GHA: correction'
2485 0x01A3 'LATIN SMALL LETTER GHA: correction'
2489 A map to the empty string means that there is no alias defined for the code
2494 is like C<"s"> in that all the map array elements are scalars, but here they are
2495 restricted to all being integers, and some have to be adjusted (hence the name
2496 C<"a">) to get the correct result. For example, in:
2498 my ($uppers_ranges_ref, $uppers_maps_ref, $format, $default)
2499 = prop_invmap("Simple_Uppercase_Mapping");
2501 the returned arrays look like this:
2503 @$uppers_ranges_ref @$uppers_maps_ref Note
2505 97 65 'a' maps to 'A', b => B ...
2507 181 924 MICRO SIGN => Greek Cap MU
2511 and C<$default> is 0.
2513 Let's start with the second line. It says that the uppercase of code point 97
2514 is 65; or C<uc("a")> == "A". But the line is for the entire range of code
2515 points 97 through 122. To get the mapping for any code point in this range,
2516 you take the offset it has from the beginning code point of the range, and add
2517 that to the mapping for that first code point. So, the mapping for 122 ("z")
2518 is derived by taking the offset of 122 from 97 (=25) and adding that to 65,
2519 yielding 90 ("z"). Likewise for everything in between.
2521 Requiring this simple adjustment allows the returned arrays to be
2522 significantly smaller than otherwise, up to a factor of 10, speeding up
2523 searching through them.
2525 Ranges that map to C<$default>, C<"0">, behave somewhat differently. For
2526 these, each code point maps to itself. So, in the first line in the example,
2527 S<C<ord(uc(chr(0)))>> is 0, S<C<ord(uc(chr(1)))>> is 1, ..
2528 S<C<ord(uc(chr(96)))>> is 96.
2532 means that some of the map array elements have the form given by C<"a">, and
2533 the rest are ordered lists of code points.
2536 my ($uppers_ranges_ref, $uppers_maps_ref, $format, $default)
2537 = prop_invmap("Uppercase_Mapping");
2539 the returned arrays look like this:
2541 @$uppers_ranges_ref @$uppers_maps_ref
2548 0x0149 [ 0x02BC 0x004E ]
2553 This is the full Uppercase_Mapping property (as opposed to the
2554 Simple_Uppercase_Mapping given in the example for format C<"a">). The only
2555 difference between the two in the ranges shown is that the code point at
2556 0x0149 (LATIN SMALL LETTER N PRECEDED BY APOSTROPHE) maps to a string of two
2557 characters, 0x02BC (MODIFIER LETTER APOSTROPHE) followed by 0x004E (LATIN
2560 No adjustments are needed to entries that are references to arrays; each such
2561 entry will have exactly one element in its range, so the offset is always 0.
2563 The fourth (index [3]) element (C<$default>) in the list returned for this
2568 This is like C<"a">, but some elements are the empty string, and should not be
2570 The one internal Perl property accessible by C<prop_invmap> is of this type:
2571 "Perl_Decimal_Digit" returns an inversion map which gives the numeric values
2572 that are represented by the Unicode decimal digit characters. Characters that
2573 don't represent decimal digits map to the empty string, like so:
2588 This means that the code points from 0 to 0x2F do not represent decimal digits;
2589 the code point 0x30 (DIGIT ZERO) represents 0; code point 0x31, (DIGIT ONE),
2590 represents 0+1-0 = 1; ... code point 0x39, (DIGIT NINE), represents 0+9-0 = 9;
2591 ... code points 0x3A through 0x65F do not represent decimal digits; 0x660
2592 (ARABIC-INDIC DIGIT ZERO), represents 0; ... 0x07C1 (NKO DIGIT ONE),
2593 represents 0+1-0 = 1 ...
2595 The fourth (index [3]) element (C<$default>) in the list returned for this
2596 format is the empty string.
2600 is a combination of the C<"al"> type and the C<"ae"> type. Some of
2601 the map array elements have the forms given by C<"al">, and
2602 the rest are the empty string. The property C<NFKC_Casefold> has this form.
2603 An example slice is:
2605 @$ranges_ref @$maps_ref Note
2607 0x00AA 97 FEMININE ORDINAL INDICATOR => 'a'
2609 0x00AD SOFT HYPHEN => ""
2611 0x00AF [ 0x0020, 0x0304 ] MACRON => SPACE . COMBINING MACRON
2615 The fourth (index [3]) element (C<$default>) in the list returned for this
2620 means that all the elements of the map array are either rational numbers or
2621 the string C<"NaN">, meaning "Not a Number". A rational number is either an
2622 integer, or two integers separated by a solidus (C<"/">). The second integer
2623 represents the denominator of the division implied by the solidus, and is
2624 actually always positive, so it is guaranteed not to be 0 and to not be
2625 signed. When the element is a plain integer (without the
2626 solidus), it may need to be adjusted to get the correct value by adding the
2627 offset, just as other C<"a"> properties. No adjustment is needed for
2628 fractions, as the range is guaranteed to have just a single element, and so
2629 the offset is always 0.
2631 If you want to convert the returned map to entirely scalar numbers, you
2632 can use something like this:
2634 my ($invlist_ref, $invmap_ref, $format) = prop_invmap($property);
2635 if ($format && $format eq "ar") {
2636 map { $_ = eval $_ if $_ ne 'NaN' } @$map_ref;
2639 Here's some entries from the output of the property "Nv", which has format
2642 @numerics_ranges @numerics_maps Note
2644 0x30 0 DIGIT 0 .. DIGIT 9
2646 0xB2 2 SUPERSCRIPTs 2 and 3
2648 0xB9 1 SUPERSCRIPT 1
2650 0xBC 1/4 VULGAR FRACTION 1/4
2651 0xBD 1/2 VULGAR FRACTION 1/2
2652 0xBE 3/4 VULGAR FRACTION 3/4
2654 0x660 0 ARABIC-INDIC DIGIT ZERO .. NINE
2657 The fourth (index [3]) element (C<$default>) in the list returned for this
2662 means the Name property. All the elements of the map array are simple
2663 scalars, but some of them contain special strings that require more work to
2664 get the actual name.
2668 CJK UNIFIED IDEOGRAPH-<code point>
2670 mean that the name for the code point is "CJK UNIFIED IDEOGRAPH-"
2671 with the code point (expressed in hexadecimal) appended to it, like "CJK
2672 UNIFIED IDEOGRAPH-3403" (similarly for S<C<CJK COMPATIBILITY IDEOGRAPH-E<lt>code
2679 means that the name is algorithmically calculated. This is easily done by
2680 the function L<charnames/charnames::viacode(code)>.
2682 Note that for control characters (C<Gc=cc>), Unicode's data files have the
2683 string "C<E<lt>controlE<gt>>", but the real name of each of these characters is the empty
2684 string. This function returns that real name, the empty string. (There are
2685 names for these characters, but they are considered aliases, not the Name
2686 property name, and are contained in the C<Name_Alias> property.)
2690 means the Decomposition_Mapping property. This property is like C<"al">
2691 properties, except that one of the scalar elements is of the form:
2695 This signifies that this entry should be replaced by the decompositions for
2696 all the code points whose decomposition is algorithmically calculated. (All
2697 of them are currently in one range and no others outside the range are likely
2698 to ever be added to Unicode; the C<"n"> format
2699 has this same entry.) These can be generated via the function
2700 L<Unicode::Normalize::NFD()|Unicode::Normalize>.
2702 Note that the mapping is the one that is specified in the Unicode data files,
2703 and to get the final decomposition, it may need to be applied recursively.
2705 The fourth (index [3]) element (C<$default>) in the list returned for this
2710 Note that a format begins with the letter "a" if and only the property it is
2711 for requires adjustments by adding the offsets in multi-element ranges. For
2712 all these properties, an entry should be adjusted only if the map is a scalar
2713 which is an integer. That is, it must match the regular expression:
2717 Further, the first element in a range never needs adjustment, as the
2718 adjustment would be just adding 0.
2720 A binary search such as that provided by L</search_invlist()>, can be used to
2721 quickly find a code point in the inversion list, and hence its corresponding
2724 The final, fourth element (index [3], assigned to C<$default> in the "block"
2725 example) in the four element list returned by this function is used with the
2726 C<"a"> format types; it may also be useful for applications
2727 that wish to convert the returned inversion map data structure into some
2728 other, such as a hash. It gives the mapping that most code points map to
2729 under the property. If you establish the convention that any code point not
2730 explicitly listed in your data structure maps to this value, you can
2731 potentially make your data structure much smaller. As you construct your data
2732 structure from the one returned by this function, simply ignore those ranges
2733 that map to this value. For example, to
2734 convert to the data structure searchable by L</charinrange()>, you can follow
2735 this recipe for properties that don't require adjustments:
2737 my ($list_ref, $map_ref, $format, $default) = prop_invmap($property);
2740 # Look at each element in the list, but the -2 is needed because we
2741 # look at $i+1 in the loop, and the final element is guaranteed to map
2742 # to $default by prop_invmap(), so we would skip it anyway.
2743 for my $i (0 .. @$list_ref - 2) {
2744 next if $map_ref->[$i] eq $default;
2745 push @range_list, [ $list_ref->[$i],
2751 print charinrange(\@range_list, $code_point), "\n";
2753 With this, C<charinrange()> will return C<undef> if its input code point maps
2754 to C<$default>. You can avoid this by omitting the C<next> statement, and adding
2755 a line after the loop to handle the final element of the inversion map.
2757 Similarly, this recipe can be used for properties that do require adjustments:
2759 for my $i (0 .. @$list_ref - 2) {
2760 next if $map_ref->[$i] eq $default;
2762 # prop_invmap() guarantees that if the mapping is to an array, the
2763 # range has just one element, so no need to worry about adjustments.
2764 if (ref $map_ref->[$i]) {
2766 [ $list_ref->[$i], $list_ref->[$i], $map_ref->[$i] ];
2768 else { # Otherwise each element is actually mapped to a separate
2769 # value, so the range has to be split into single code point
2774 # For each code point that gets mapped to something...
2775 for my $j ($list_ref->[$i] .. $list_ref->[$i+1] -1 ) {
2777 # ... add a range consisting of just it mapping to the
2778 # original plus the adjustment, which is incremented for the
2779 # next time through the loop, as the offset increases by 1
2780 # for each element in the range
2782 [ $j, $j, $map_ref->[$i] + $adjustment++ ];
2787 Note that the inversion maps returned for the C<Case_Folding> and
2788 C<Simple_Case_Folding> properties do not include the Turkic-locale mappings.
2789 Use L</casefold()> for these.
2791 C<prop_invmap> does not know about any user-defined properties, and will
2792 return C<undef> if called with one of those.
2796 # User-defined properties could be handled with some changes to utf8_heavy.pl;
2797 # if done, consideration should be given to the fact that the user subroutine
2798 # could return different results with each call, which could lead to some
2801 # One could store things in memory so they don't have to be recalculated, but
2802 # it is unlikely this will be called often, and some properties would take up
2803 # significant memory.
2805 # These are created by mktables for this routine and stored in unicore/UCD.pl
2806 # where their structures are described.
2807 our @algorithmic_named_code_points;
2811 sub prop_invmap ($) {
2813 croak __PACKAGE__, "::prop_invmap: must be called in list context" unless wantarray;
2816 return unless defined $prop;
2818 # Fail internal properties
2819 return if $prop =~ /^_/;
2821 # The values returned by this function.
2822 my (@invlist, @invmap, $format, $missing);
2824 # The swash has two components we look at, the base list, and a hash,
2825 # named 'SPECIALS', containing any additional members whose mappings don't
2826 # fit into the base list scheme of things. These generally 'override'
2827 # any value in the base list for the same code point.
2830 require "utf8_heavy.pl";
2831 require "unicore/UCD.pl";
2835 # If there are multiple entries for a single code point
2836 my $has_multiples = 0;
2838 # Try to get the map swash for the property. They have 'To' prepended to
2839 # the property name, and 32 means we will accept 32 bit return values.
2840 # The 0 means we aren't calling this from tr///.
2841 my $swash = utf8::SWASHNEW(__PACKAGE__, "To$prop", undef, 32, 0);
2843 # If didn't find it, could be because needs a proxy. And if was the
2844 # 'Block' or 'Name' property, use a proxy even if did find it. Finding it
2845 # in these cases would be the result of the installation changing mktables
2846 # to output the Block or Name tables. The Block table gives block names
2847 # in the new-style, and this routine is supposed to return old-style block
2848 # names. The Name table is valid, but we need to execute the special code
2849 # below to add in the algorithmic-defined name entries.
2850 # And NFKCCF needs conversion, so handle that here too.
2851 if (ref $swash eq ""
2852 || $swash->{'TYPE'} =~ / ^ To (?: Blk | Na | NFKCCF ) $ /x)
2855 # Get the short name of the input property, in standard form
2856 my ($second_try) = prop_aliases($prop);
2857 return unless $second_try;
2858 $second_try = utf8::_loose_name(lc $second_try);
2860 if ($second_try eq "in") {
2862 # This property is identical to age for inversion map purposes
2866 elsif ($second_try =~ / ^ s ( cf | fc | [ltu] c ) $ /x) {
2868 # These properties use just the LIST part of the full mapping,
2869 # which includes the simple maps that are otherwise overridden by
2870 # the SPECIALS. So all we need do is to not look at the SPECIALS;
2871 # set $overrides to indicate that
2874 # The full name is the simple name stripped of its initial 's'
2877 # .. except for this case
2878 $prop = 'cf' if $prop eq 'fc';
2882 elsif ($second_try eq "blk") {
2884 # We use the old block names. Just create a fake swash from its
2888 $blocks{'LIST'} = "";
2889 $blocks{'TYPE'} = "ToBlk";
2890 $utf8::SwashInfo{ToBlk}{'missing'} = "No_Block";
2891 $utf8::SwashInfo{ToBlk}{'format'} = "s";
2893 foreach my $block (@BLOCKS) {
2894 $blocks{'LIST'} .= sprintf "%x\t%x\t%s\n",
2901 elsif ($second_try eq "na") {
2903 # Use the combo file that has all the Name-type properties in it,
2904 # extracting just the ones that are for the actual 'Name'
2905 # property. And create a fake swash from it.
2907 $names{'LIST'} = "";
2908 my $original = do "unicore/Name.pl";
2909 my $algorithm_names = \@algorithmic_named_code_points;
2911 # We need to remove the names from it that are aliases. For that
2912 # we need to also read in that table. Create a hash with the keys
2913 # being the code points, and the values being a list of the
2914 # aliases for the code point key.
2915 my ($aliases_code_points, $aliases_maps, undef, undef) =
2916 &prop_invmap('Name_Alias');
2918 for (my $i = 0; $i < @$aliases_code_points; $i++) {
2919 my $code_point = $aliases_code_points->[$i];
2920 $aliases{$code_point} = $aliases_maps->[$i];
2922 # If not already a list, make it into one, so that later we
2923 # can treat things uniformly
2924 if (! ref $aliases{$code_point}) {
2925 $aliases{$code_point} = [ $aliases{$code_point} ];
2928 # Remove the alias type from the entry, retaining just the
2930 map { s/:.*// } @{$aliases{$code_point}};
2934 foreach my $line (split "\n", $original) {
2935 my ($hex_code_point, $name) = split "\t", $line;
2937 # Weeds out all comments, blank lines, and named sequences
2938 next if $hex_code_point =~ /[^[:xdigit:]]/a;
2940 my $code_point = hex $hex_code_point;
2942 # The name of all controls is the default: the empty string.
2943 # The set of controls is immutable
2944 next if chr($code_point) =~ /[[:cntrl:]]/u;
2946 # If this is a name_alias, it isn't a name
2947 next if grep { $_ eq $name } @{$aliases{$code_point}};
2949 # If we are beyond where one of the special lines needs to
2951 while ($i < @$algorithm_names
2952 && $code_point > $algorithm_names->[$i]->{'low'})
2955 # ... then insert it, ahead of what we were about to
2957 $names{'LIST'} .= sprintf "%x\t%x\t%s\n",
2958 $algorithm_names->[$i]->{'low'},
2959 $algorithm_names->[$i]->{'high'},
2960 $algorithm_names->[$i]->{'name'};
2962 # Done with this range.
2965 # We loop until all special lines that precede the next
2966 # regular one are output.
2969 # Here, is a normal name.
2970 $names{'LIST'} .= sprintf "%x\t\t%s\n", $code_point, $name;
2971 } # End of loop through all the names
2973 $names{'TYPE'} = "ToNa";
2974 $utf8::SwashInfo{ToNa}{'missing'} = "";
2975 $utf8::SwashInfo{ToNa}{'format'} = "n";
2978 elsif ($second_try =~ / ^ ( d [mt] ) $ /x) {
2980 # The file is a combination of dt and dm properties. Create a
2981 # fake swash from the portion that we want.
2982 my $original = do "unicore/Decomposition.pl";
2985 if ($second_try eq 'dt') {
2986 $decomps{'TYPE'} = "ToDt";
2987 $utf8::SwashInfo{'ToDt'}{'missing'} = "None";
2988 $utf8::SwashInfo{'ToDt'}{'format'} = "s";
2989 } # 'dm' is handled below, with 'nfkccf'
2991 $decomps{'LIST'} = "";
2993 # This property has one special range not in the file: for the
2994 # hangul syllables. But not in Unicode version 1.
2995 UnicodeVersion() unless defined $v_unicode_version;
2996 my $done_hangul = ($v_unicode_version lt v2.0.0)
2998 : 0; # Have we done the hangul range ?
2999 foreach my $line (split "\n", $original) {
3000 my ($hex_lower, $hex_upper, $type_and_map) = split "\t", $line;
3001 my $code_point = hex $hex_lower;
3005 # The type, enclosed in <...>, precedes the mapping separated
3007 if ($type_and_map =~ / ^ < ( .* ) > \s+ (.*) $ /x) {
3008 $value = ($second_try eq 'dt') ? $1 : $2
3010 else { # If there is no type specified, it's canonical
3011 $value = ($second_try eq 'dt')
3016 # Insert the hangul range at the appropriate spot.
3017 if (! $done_hangul && $code_point > $HANGUL_BEGIN) {
3020 sprintf "%x\t%x\t%s\n",
3022 $HANGUL_BEGIN + $HANGUL_COUNT - 1,
3023 ($second_try eq 'dt')
3025 : "<hangul syllable>";
3028 if ($value =~ / / && $hex_upper ne "" && $hex_upper ne $hex_lower) {
3029 $line = sprintf("%04X\t%s\t%s", hex($hex_lower) + 1, $hex_upper, $value);
3034 # And append this to our constructed LIST.
3035 $decomps{'LIST'} .= "$hex_lower\t$hex_upper\t$value\n";
3041 elsif ($second_try ne 'nfkccf') { # Don't know this property. Fail.
3045 if ($second_try eq 'nfkccf' || $second_try eq 'dm') {
3047 # The 'nfkccf' property is stored in the old format for backwards
3048 # compatibility for any applications that has read its file
3049 # directly before prop_invmap() existed.
3050 # And the code above has extracted the 'dm' property from its file
3051 # yielding the same format. So here we convert them to adjusted
3052 # format for compatibility with the other properties similar to
3056 # We construct a new converted list.
3059 my @ranges = split "\n", $swash->{'LIST'};
3060 for (my $i = 0; $i < @ranges; $i++) {
3061 my ($hex_begin, $hex_end, $map) = split "\t", $ranges[$i];
3063 # The dm property has maps that are space separated sequences
3064 # of code points, as well as the special entry "<hangul
3065 # syllable>, which also contains a blank.
3066 my @map = split " ", $map;
3069 # If it's just the special entry, append as-is.
3070 if ($map eq '<hangul syllable>') {
3071 $list .= "$ranges[$i]\n";
3075 # These should all be single-element ranges.
3076 croak __PACKAGE__, "::prop_invmap: Not expecting a mapping with multiple code points in a multi-element range, $ranges[$i]" if $hex_end ne "" && $hex_end ne $hex_begin;
3078 # Convert them to decimal, as that's what's expected.
3079 $list .= "$hex_begin\t\t"
3080 . join(" ", map { hex } @map)
3086 # Here, the mapping doesn't have a blank, is for a single code
3088 my $begin = hex $hex_begin;
3089 my $end = (defined $hex_end && $hex_end ne "")
3093 # Again, the output is to be in decimal.
3094 my $decimal_map = hex $map;
3096 # We know that multi-element ranges with the same mapping
3097 # should not be adjusted, as after the adjustment
3098 # multi-element ranges are for consecutive increasing code
3099 # points. Further, the final element in the list won't be
3100 # adjusted, as there is nothing after it to include in the
3102 if ($begin != $end || $i == @ranges -1) {
3104 # So just convert these to single-element ranges
3105 foreach my $code_point ($begin .. $end) {
3106 $list .= sprintf("%04X\t\t%d\n",
3107 $code_point, $decimal_map);
3112 # Here, we have a candidate for adjusting. What we do is
3113 # look through the subsequent adjacent elements in the
3114 # input. If the map to the next one differs by 1 from the
3115 # one before, then we combine into a larger range with the
3116 # initial map. Loop doing this until we find one that
3117 # can't be combined.
3119 my $offset = 0; # How far away are we from the initial
3121 my $squished = 0; # ? Did we squish at least two
3122 # elements together into one range
3123 for ( ; $i < @ranges; $i++) {
3124 my ($next_hex_begin, $next_hex_end, $next_map)
3125 = split "\t", $ranges[$i+1];
3127 # In the case of 'dm', the map may be a sequence of
3128 # multiple code points, which are never combined with
3130 last if $next_map =~ / /;
3133 my $next_decimal_map = hex $next_map;
3135 # If the next map is not next in sequence, it
3136 # shouldn't be combined.
3137 last if $next_decimal_map != $decimal_map + $offset;
3139 my $next_begin = hex $next_hex_begin;
3141 # Likewise, if the next element isn't adjacent to the
3142 # previous one, it shouldn't be combined.
3143 last if $next_begin != $begin + $offset;
3145 my $next_end = (defined $next_hex_end
3146 && $next_hex_end ne "")
3150 # And finally, if the next element is a multi-element
3151 # range, it shouldn't be combined.
3152 last if $next_end != $next_begin;
3154 # Here, we will combine. Loop to see if we should
3155 # combine the next element too.
3161 # Here, 'i' is the element number of the last element to
3162 # be combined, and the range is single-element, or we
3163 # wouldn't be combining. Get it's code point.
3164 my ($hex_end, undef, undef) = split "\t", $ranges[$i];
3165 $list .= "$hex_begin\t$hex_end\t$decimal_map\n";
3168 # Here, no combining done. Just append the initial
3169 # (and current) values.
3170 $list .= "$hex_begin\t\t$decimal_map\n";
3173 } # End of loop constructing the converted list
3175 # Finish up the data structure for our converted swash
3176 my $type = ($second_try eq 'nfkccf') ? 'ToNFKCCF' : 'ToDm';
3177 $revised_swash{'LIST'} = $list;
3178 $revised_swash{'TYPE'} = $type;
3179 $revised_swash{'SPECIALS'} = $swash->{'SPECIALS'};
3180 $swash = \%revised_swash;
3182 $utf8::SwashInfo{$type}{'missing'} = 0;
3183 $utf8::SwashInfo{$type}{'format'} = 'a';
3187 if ($swash->{'EXTRAS'}) {
3188 carp __PACKAGE__, "::prop_invmap: swash returned for $prop unexpectedly has EXTRAS magic";
3192 # Here, have a valid swash return. Examine it.
3193 my $returned_prop = $swash->{'TYPE'};
3195 # All properties but binary ones should have 'missing' and 'format'
3197 $missing = $utf8::SwashInfo{$returned_prop}{'missing'};
3198 $missing = 'N' unless defined $missing;
3200 $format = $utf8::SwashInfo{$returned_prop}{'format'};
3201 $format = 'b' unless defined $format;
3203 my $requires_adjustment = $format =~ /^a/;
3205 if ($swash->{'LIST'} =~ /^V/) {
3206 @invlist = split "\n", $swash->{'LIST'} =~ s/ \s* (?: \# .* )? $ //xmgr;
3208 foreach my $i (0 .. @invlist - 1) {
3209 $invmap[$i] = ($i % 2 == 0) ? 'Y' : 'N'
3212 # The map includes lines for all code points; add one for the range
3213 # from 0 to the first Y.
3214 if ($invlist[0] != 0) {
3215 unshift @invlist, 0;
3216 unshift @invmap, 'N';
3220 # The LIST input lines look like:
3223 # 0375\t0377\tGreek # [3]
3224 # 037A\t037D\tGreek # [4]
3229 # Convert them to like
3238 # For binary properties, the final non-comment column is absent, and
3239 # assumed to be 'Y'.
3241 foreach my $range (split "\n", $swash->{'LIST'}) {
3242 $range =~ s/ \s* (?: \# .* )? $ //xg; # rmv trailing space, comments
3244 # Find the beginning and end of the range on the line
3245 my ($hex_begin, $hex_end, $map) = split "\t", $range;
3246 my $begin = hex $hex_begin;
3247 no warnings 'portable';
3248 my $end = (defined $hex_end && $hex_end ne "")
3252 # Each time through the loop (after the first):
3253 # $invlist[-2] contains the beginning of the previous range processed
3254 # $invlist[-1] contains the end+1 of the previous range processed
3255 # $invmap[-2] contains the value of the previous range processed
3256 # $invmap[-1] contains the default value for missing ranges
3259 # Thus, things are set up for the typical case of a new
3260 # non-adjacent range of non-missings to be added. But, if the new
3261 # range is adjacent, it needs to replace the [-1] element; and if
3262 # the new range is a multiple value of the previous one, it needs
3263 # to be added to the [-2] map element.
3265 # The first time through, everything will be empty. If the
3266 # property doesn't have a range that begins at 0, add one that
3271 push @invmap, $missing;
3274 elsif (@invlist > 1 && $invlist[-2] == $begin) {
3276 # Here we handle the case where the input has multiple entries
3277 # for each code point. mktables should have made sure that
3278 # each such range contains only one code point. At this
3279 # point, $invlist[-1] is the $missing that was added at the
3280 # end of the last loop iteration, and [-2] is the last real
3281 # input code point, and that code point is the same as the one
3282 # we are adding now, making the new one a multiple entry. Add
3283 # it to the existing entry, either by pushing it to the
3284 # existing list of multiple entries, or converting the single
3285 # current entry into a list with both on it. This is all we
3286 # need do for this iteration.
3288 if ($end != $begin) {
3289 croak __PACKAGE__, ":prop_invmap: Multiple maps per code point in '$prop' require single-element ranges: begin=$begin, end=$end, map=$map";
3291 if (! ref $invmap[-2]) {
3292 $invmap[-2] = [ $invmap[-2], $map ];
3295 push @{$invmap[-2]}, $map;
3300 elsif ($invlist[-1] == $begin) {
3302 # If the input isn't in the most compact form, so that there
3303 # are two adjacent ranges that map to the same thing, they
3304 # should be combined (EXCEPT where the arrays require
3305 # adjustments, in which case everything is already set up
3306 # correctly). This happens in our constructed dt mapping, as
3307 # Element [-2] is the map for the latest range so far
3308 # processed. Just set the beginning point of the map to
3309 # $missing (in invlist[-1]) to 1 beyond where this range ends.
3313 # we have set it up so that it looks like
3317 # We now see that it should be
3320 if (! $requires_adjustment && @invlist > 1 && ( (defined $map)
3321 ? $invmap[-2] eq $map
3322 : $invmap[-2] eq 'Y'))
3324 $invlist[-1] = $end + 1;
3328 # Here, the range started in the previous iteration that maps
3329 # to $missing starts at the same code point as this range.
3330 # That means there is no gap to fill that that range was
3331 # intended for, so we just pop it off the parallel arrays.
3336 # Add the range beginning, and the range's map.
3337 push @invlist, $begin;
3338 if ($returned_prop eq 'ToDm') {
3340 # The decomposition maps are either a line like <hangul
3341 # syllable> which are to be taken as is; or a sequence of code
3342 # points in hex and separated by blanks. Convert them to
3343 # decimal, and if there is more than one, use an anonymous
3345 if ($map =~ /^ < /x) {
3349 my @map = split " ", $map;
3351 push @invmap, $map[0];
3354 push @invmap, \@map;
3360 # Otherwise, convert hex formatted list entries to decimal;
3361 # add a 'Y' map for the missing value in binary properties, or
3362 # otherwise, use the input map unchanged.
3363 $map = ($format eq 'x' || $format eq 'ax')
3371 # We just started a range. It ends with $end. The gap between it
3372 # and the next element in the list must be filled with a range
3373 # that maps to the default value. If there is no gap, the next
3374 # iteration will pop this, unless there is no next iteration, and
3375 # we have filled all of the Unicode code space, so check for that
3377 if ($end < $Unicode::UCD::MAX_CP) {
3378 push @invlist, $end + 1;
3379 push @invmap, $missing;
3384 # If the property is empty, make all code points use the value for missing
3388 push @invmap, $missing;
3391 # The final element is always for just the above-Unicode code points. If
3392 # not already there, add it. It merely splits the current final range
3393 # that extends to infinity into two elements, each with the same map.
3394 # (This is to conform with the API that says the final element is for
3395 # $MAX_UNICODE_CODEPOINT + 1 .. INFINITY.)
3396 if ($invlist[-1] != $MAX_UNICODE_CODEPOINT + 1) {
3397 push @invmap, $invmap[-1];
3398 push @invlist, $MAX_UNICODE_CODEPOINT + 1;
3401 # The second component of the map are those values that require
3402 # non-standard specification, stored in SPECIALS. These override any
3403 # duplicate code points in LIST. If we are using a proxy, we may have
3404 # already set $overrides based on the proxy.
3405 $overrides = $swash->{'SPECIALS'} unless defined $overrides;
3408 # A negative $overrides implies that the SPECIALS should be ignored,
3409 # and a simple 'a' list is the value.
3410 if ($overrides < 0) {
3415 # Currently, all overrides are for properties that normally map to
3416 # single code points, but now some will map to lists of code
3417 # points (but there is an exception case handled below).
3420 # Look through the overrides.
3421 foreach my $cp_maybe_utf8 (keys %$overrides) {
3425 # If the overrides came from SPECIALS, the code point keys are
3427 if ($overrides == $swash->{'SPECIALS'}) {
3428 $cp = unpack("C0U", $cp_maybe_utf8);
3429 @map = unpack "U0U*", $swash->{'SPECIALS'}{$cp_maybe_utf8};
3431 # The empty string will show up unpacked as an empty
3433 $format = 'ale' if @map == 0;
3437 # But if we generated the overrides, we didn't bother to
3438 # pack them, and we, so far, do this only for properties
3439 # that are 'a' ones.
3440 $cp = $cp_maybe_utf8;
3441 @map = hex $overrides->{$cp};
3445 # Find the range that the override applies to.
3446 my $i = search_invlist(\@invlist, $cp);
3447 if ($cp < $invlist[$i] || $cp >= $invlist[$i + 1]) {
3448 croak __PACKAGE__, "::prop_invmap: wrong_range, cp=$cp; i=$i, current=$invlist[$i]; next=$invlist[$i + 1]"
3451 # And what that range currently maps to
3452 my $cur_map = $invmap[$i];
3454 # If there is a gap between the next range and the code point
3455 # we are overriding, we have to add elements to both arrays to
3456 # fill that gap, using the map that applies to it, which is
3457 # $cur_map, since it is part of the current range.
3458 if ($invlist[$i + 1] > $cp + 1) {
3460 #say "Before splice:";
3461 #say 'i-2=[', $i-2, ']', sprintf("%04X maps to %s", $invlist[$i-2], $invmap[$i-2]) if $i >= 2;
3462 #say 'i-1=[', $i-1, ']', sprintf("%04X maps to %s", $invlist[$i-1], $invmap[$i-1]) if $i >= 1;
3463 #say 'i =[', $i, ']', sprintf("%04X maps to %s", $invlist[$i], $invmap[$i]);
3464 #say 'i+1=[', $i+1, ']', sprintf("%04X maps to %s", $invlist[$i+1], $invmap[$i+1]) if $i < @invlist + 1;
3465 #say 'i+2=[', $i+2, ']', sprintf("%04X maps to %s", $invlist[$i+2], $invmap[$i+2]) if $i < @invlist + 2;
3467 splice @invlist, $i + 1, 0, $cp + 1;
3468 splice @invmap, $i + 1, 0, $cur_map;
3470 #say "After splice:";
3471 #say 'i-2=[', $i-2, ']', sprintf("%04X maps to %s", $invlist[$i-2], $invmap[$i-2]) if $i >= 2;
3472 #say 'i-1=[', $i-1, ']', sprintf("%04X maps to %s", $invlist[$i-1], $invmap[$i-1]) if $i >= 1;
3473 #say 'i =[', $i, ']', sprintf("%04X maps to %s", $invlist[$i], $invmap[$i]);
3474 #say 'i+1=[', $i+1, ']', sprintf("%04X maps to %s", $invlist[$i+1], $invmap[$i+1]) if $i < @invlist + 1;
3475 #say 'i+2=[', $i+2, ']', sprintf("%04X maps to %s", $invlist[$i+2], $invmap[$i+2]) if $i < @invlist + 2;
3478 # If the remaining portion of the range is multiple code
3479 # points (ending with the one we are replacing, guaranteed by
3480 # the earlier splice). We must split it into two
3481 if ($invlist[$i] < $cp) {
3482 $i++; # Compensate for the new element
3485 #say "Before splice:";
3486 #say 'i-2=[', $i-2, ']', sprintf("%04X maps to %s", $invlist[$i-2], $invmap[$i-2]) if $i >= 2;
3487 #say 'i-1=[', $i-1, ']', sprintf("%04X maps to %s", $invlist[$i-1], $invmap[$i-1]) if $i >= 1;
3488 #say 'i =[', $i, ']', sprintf("%04X maps to %s", $invlist[$i], $invmap[$i]);
3489 #say 'i+1=[', $i+1, ']', sprintf("%04X maps to %s", $invlist[$i+1], $invmap[$i+1]) if $i < @invlist + 1;
3490 #say 'i+2=[', $i+2, ']', sprintf("%04X maps to %s", $invlist[$i+2], $invmap[$i+2]) if $i < @invlist + 2;
3492 splice @invlist, $i, 0, $cp;
3493 splice @invmap, $i, 0, 'dummy';
3495 #say "After splice:";
3496 #say 'i-2=[', $i-2, ']', sprintf("%04X maps to %s", $invlist[$i-2], $invmap[$i-2]) if $i >= 2;
3497 #say 'i-1=[', $i-1, ']', sprintf("%04X maps to %s", $invlist[$i-1], $invmap[$i-1]) if $i >= 1;
3498 #say 'i =[', $i, ']', sprintf("%04X maps to %s", $invlist[$i], $invmap[$i]);
3499 #say 'i+1=[', $i+1, ']', sprintf("%04X maps to %s", $invlist[$i+1], $invmap[$i+1]) if $i < @invlist + 1;
3500 #say 'i+2=[', $i+2, ']', sprintf("%04X maps to %s", $invlist[$i+2], $invmap[$i+2]) if $i < @invlist + 2;
3503 # Here, the range we are overriding contains a single code
3504 # point. The result could be the empty string, a single
3505 # value, or a list. If the last case, we use an anonymous
3507 $invmap[$i] = (scalar @map == 0)
3515 elsif ($format eq 'x') {
3517 # All hex-valued properties are really to code points, and have been
3518 # converted to decimal.
3521 elsif ($returned_prop eq 'ToDm') {
3524 elsif ($format eq 'sw') { # blank-separated elements to form a list.
3525 map { $_ = [ split " ", $_ ] if $_ =~ / / } @invmap;
3528 elsif ($returned_prop eq 'ToNameAlias') {
3530 # This property currently doesn't have any lists, but theoretically
3534 elsif ($returned_prop eq 'ToPerlDecimalDigit') {
3537 elsif ($returned_prop eq 'ToNv') {
3539 # The one property that has this format is stored as a delta, so needs
3540 # to indicate that need to add code point to it.
3543 elsif ($format ne 'n' && $format ne 'a') {
3545 # All others are simple scalars
3548 if ($has_multiples && $format !~ /l/) {
3549 croak __PACKAGE__, "::prop_invmap: Wrong format '$format' for prop_invmap('$prop'); should indicate has lists";
3552 return (\@invlist, \@invmap, $format, $missing);
3555 sub search_invlist {
3559 =head2 B<search_invlist()>
3561 use Unicode::UCD qw(prop_invmap prop_invlist);
3562 use Unicode::UCD 'search_invlist';
3564 my @invlist = prop_invlist($property_name);
3565 print $code_point, ((search_invlist(\@invlist, $code_point) // -1) % 2)
3568 " in $property_name\n";
3570 my ($blocks_ranges_ref, $blocks_map_ref) = prop_invmap("Block");
3571 my $index = search_invlist($blocks_ranges_ref, $code_point);
3572 print "$code_point is in block ", $blocks_map_ref->[$index], "\n";
3574 C<search_invlist> is used to search an inversion list returned by
3575 C<prop_invlist> or C<prop_invmap> for a particular L</code point argument>.
3576 C<undef> is returned if the code point is not found in the inversion list
3577 (this happens only when it is not a legal L<code point argument>, or is less
3578 than the list's first element). A warning is raised in the first instance.
3580 Otherwise, it returns the index into the list of the range that contains the
3581 code point.; that is, find C<i> such that
3583 list[i]<= code_point < list[i+1].
3585 As explained in L</prop_invlist()>, whether a code point is in the list or not
3586 depends on if the index is even (in) or odd (not in). And as explained in
3587 L</prop_invmap()>, the index is used with the returned parallel array to find
3593 my $list_ref = shift;
3594 my $input_code_point = shift;
3595 my $code_point = _getcode($input_code_point);
3597 if (! defined $code_point) {
3598 carp __PACKAGE__, "::search_invlist: unknown code '$input_code_point'";
3602 my $max_element = @$list_ref - 1;
3604 # Return undef if list is empty or requested item is before the first element.
3605 return if $max_element < 0;
3606 return if $code_point < $list_ref->[0];
3608 # Short cut something at the far-end of the table. This also allows us to
3609 # refer to element [$i+1] without fear of being out-of-bounds in the loop
3611 return $max_element if $code_point >= $list_ref->[$max_element];
3613 use integer; # want integer division
3615 my $i = $max_element / 2;
3618 my $upper = $max_element;
3621 if ($code_point >= $list_ref->[$i]) {
3623 # Here we have met the lower constraint. We can quit if we
3624 # also meet the upper one.
3625 last if $code_point < $list_ref->[$i+1];
3627 $lower = $i; # Still too low.
3632 # Here, $code_point < $list_ref[$i], so look lower down.
3636 # Split search domain in half to try again.
3637 my $temp = ($upper + $lower) / 2;
3639 # No point in continuing unless $i changes for next time
3641 return $i if $temp == $i;
3643 } # End of while loop
3645 # Here we have found the offset
3649 =head2 Unicode::UCD::UnicodeVersion
3651 This returns the version of the Unicode Character Database, in other words, the
3652 version of the Unicode standard the database implements. The version is a
3653 string of numbers delimited by dots (C<'.'>).
3659 sub UnicodeVersion {
3660 unless (defined $UNICODEVERSION) {
3661 openunicode(\$VERSIONFH, "version");
3663 chomp($UNICODEVERSION = <$VERSIONFH>);
3665 croak __PACKAGE__, "::VERSION: strange version '$UNICODEVERSION'"
3666 unless $UNICODEVERSION =~ /^\d+(?:\.\d+)+$/;
3668 $v_unicode_version = pack "C*", split /\./, $UNICODEVERSION;
3669 return $UNICODEVERSION;
3672 =head2 B<Blocks versus Scripts>
3674 The difference between a block and a script is that scripts are closer
3675 to the linguistic notion of a set of code points required to present
3676 languages, while block is more of an artifact of the Unicode code point
3677 numbering and separation into blocks of consecutive code points (so far the
3678 size of a block is some multiple of 16, like 128 or 256).
3680 For example the Latin B<script> is spread over several B<blocks>, such
3681 as C<Basic Latin>, C<Latin 1 Supplement>, C<Latin Extended-A>, and
3682 C<Latin Extended-B>. On the other hand, the Latin script does not
3683 contain all the characters of the C<Basic Latin> block (also known as
3684 ASCII): it includes only the letters, and not, for example, the digits
3687 For blocks see L<http://www.unicode.org/Public/UNIDATA/Blocks.txt>
3689 For scripts see UTR #24: L<http://www.unicode.org/unicode/reports/tr24/>
3691 =head2 B<Matching Scripts and Blocks>
3693 Scripts are matched with the regular-expression construct
3694 C<\p{...}> (e.g. C<\p{Tibetan}> matches characters of the Tibetan script),
3695 while C<\p{Blk=...}> is used for blocks (e.g. C<\p{Blk=Tibetan}> matches
3696 any of the 256 code points in the Tibetan block).
3698 =head2 Old-style versus new-style block names
3700 Unicode publishes the names of blocks in two different styles, though the two
3701 are equivalent under Unicode's loose matching rules.
3703 The original style uses blanks and hyphens in the block names (except for
3704 C<No_Block>), like so:
3706 Miscellaneous Mathematical Symbols-B
3708 The newer style replaces these with underscores, like this:
3710 Miscellaneous_Mathematical_Symbols_B
3712 This newer style is consistent with the values of other Unicode properties.
3713 To preserve backward compatibility, all the functions in Unicode::UCD that
3714 return block names (except one) return the old-style ones. That one function,
3715 L</prop_value_aliases()> can be used to convert from old-style to new-style:
3717 my $new_style = prop_values_aliases("block", $old_style);
3719 Perl also has single-form extensions that refer to blocks, C<In_Cyrillic>,
3720 meaning C<Block=Cyrillic>. These have always been written in the new style.
3722 To convert from new-style to old-style, follow this recipe:
3724 $old_style = charblock((prop_invlist("block=$new_style"))[0]);
3726 (which finds the range of code points in the block using C<prop_invlist>,
3727 gets the lower end of the range (0th element) and then looks up the old name
3728 for its block using C<charblock>).
3730 Note that starting in Unicode 6.1, many of the block names have shorter
3731 synonyms. These are always given in the new style.
3735 Jarkko Hietaniemi. Now maintained by perl5 porters.