5 no warnings 'surrogate'; # surrogates can be inputs to this
7 use Unicode::Normalize qw(getCombinClass NFD);
11 use Storable qw(dclone);
15 our @ISA = qw(Exporter);
17 our @EXPORT_OK = qw(charinfo
19 charblocks charscripts
21 general_categories bidi_types
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 'casespec';
48 my $casespec = casespec(0xFB00);
50 use Unicode::UCD 'charblock';
51 my $charblock = charblock($codepoint);
53 use Unicode::UCD 'charscript';
54 my $charscript = charscript($codepoint);
56 use Unicode::UCD 'charblocks';
57 my $charblocks = charblocks();
59 use Unicode::UCD 'charscripts';
60 my $charscripts = charscripts();
62 use Unicode::UCD qw(charscript charinrange);
63 my $range = charscript($script);
64 print "looks like $script\n" if charinrange($range, $codepoint);
66 use Unicode::UCD qw(general_categories bidi_types);
67 my $categories = general_categories();
68 my $types = bidi_types();
70 use Unicode::UCD 'prop_aliases';
71 my @space_names = prop_aliases("space");
73 use Unicode::UCD 'prop_value_aliases';
74 my @gc_punct_names = prop_value_aliases("Gc", "Punct");
76 use Unicode::UCD 'prop_invlist';
77 my @puncts = prop_invlist("gc=punctuation");
79 use Unicode::UCD 'prop_invmap';
80 my ($list_ref, $map_ref, $format, $missing)
81 = prop_invmap("General Category");
83 use Unicode::UCD 'compexcl';
84 my $compexcl = compexcl($codepoint);
86 use Unicode::UCD 'namedseq';
87 my $namedseq = namedseq($named_sequence_name);
89 my $unicode_version = Unicode::UCD::UnicodeVersion();
91 my $convert_to_numeric =
92 Unicode::UCD::num("\N{RUMI DIGIT ONE}\N{RUMI DIGIT TWO}");
96 The Unicode::UCD module offers a series of functions that
97 provide a simple interface to the Unicode
100 =head2 code point argument
102 Some of the functions are called with a I<code point argument>, which is either
103 a decimal or a hexadecimal scalar designating a Unicode code point, or C<U+>
104 followed by hexadecimals designating a Unicode code point. In other words, if
105 you want a code point to be interpreted as a hexadecimal number, you must
106 prefix it with either C<0x> or C<U+>, because a string like e.g. C<123> will be
107 interpreted as a decimal code point. Note that the largest code point in
119 my ($rfh, @path) = @_;
121 unless (defined $$rfh) {
124 $f = File::Spec->catfile($d, "unicore", @path);
125 last if open($$rfh, $f);
128 croak __PACKAGE__, ": failed to find ",
129 File::Spec->catfile(@path), " in @INC"
137 use Unicode::UCD 'charinfo';
139 my $charinfo = charinfo(0x41);
141 This returns information about the input L</code point argument>
142 as a reference to a hash of fields as defined by the Unicode
143 standard. If the L</code point argument> is not assigned in the standard
144 (i.e., has the general category C<Cn> meaning C<Unassigned>)
145 or is a non-character (meaning it is guaranteed to never be assigned in
147 C<undef> is returned.
149 Fields that aren't applicable to the particular code point argument exist in the
150 returned hash, and are empty.
152 The keys in the hash with the meanings of their values are:
158 the input L</code point argument> expressed in hexadecimal, with leading zeros
159 added if necessary to make it contain at least four hexdigits
163 name of I<code>, all IN UPPER CASE.
164 Some control-type code points do not have names.
165 This field will be empty for C<Surrogate> and C<Private Use> code points,
166 and for the others without a name,
167 it will contain a description enclosed in angle brackets, like
168 C<E<lt>controlE<gt>>.
173 The short name of the general category of I<code>.
174 This will match one of the keys in the hash returned by L</general_categories()>.
176 The L</prop_value_aliases()> function can be used to get all the synonyms
177 of the category name.
181 the combining class number for I<code> used in the Canonical Ordering Algorithm.
182 For Unicode 5.1, this is described in Section 3.11 C<Canonical Ordering Behavior>
184 L<http://www.unicode.org/versions/Unicode5.1.0/>
186 The L</prop_value_aliases()> function can be used to get all the synonyms
187 of the combining class number.
191 bidirectional type of I<code>.
192 This will match one of the keys in the hash returned by L</bidi_types()>.
194 The L</prop_value_aliases()> function can be used to get all the synonyms
195 of the bidi type name.
197 =item B<decomposition>
199 is empty if I<code> has no decomposition; or is one or more codes
200 (separated by spaces) that, taken in order, represent a decomposition for
201 I<code>. Each has at least four hexdigits.
202 The codes may be preceded by a word enclosed in angle brackets then a space,
203 like C<E<lt>compatE<gt> >, giving the type of decomposition
205 This decomposition may be an intermediate one whose components are also
206 decomposable. Use L<Unicode::Normalize> to get the final decomposition.
210 if I<code> is a decimal digit this is its integer numeric value
214 if I<code> represents some other digit-like number, this is its integer
219 if I<code> represents a whole or rational number, this is its numeric value.
220 Rational values are expressed as a string like C<1/4>.
224 C<Y> or C<N> designating if I<code> is mirrored in bidirectional text
228 name of I<code> in the Unicode 1.0 standard if one
229 existed for this code point and is different from the current name
233 As of Unicode 6.0, this is always empty.
237 is empty if there is no single code point uppercase mapping for I<code>
238 (its uppercase mapping is itself);
239 otherwise it is that mapping expressed as at least four hexdigits.
240 (L</casespec()> should be used in addition to B<charinfo()>
241 for case mappings when the calling program can cope with multiple code point
246 is empty if there is no single code point lowercase mapping for I<code>
247 (its lowercase mapping is itself);
248 otherwise it is that mapping expressed as at least four hexdigits.
249 (L</casespec()> should be used in addition to B<charinfo()>
250 for case mappings when the calling program can cope with multiple code point
255 is empty if there is no single code point titlecase mapping for I<code>
256 (its titlecase mapping is itself);
257 otherwise it is that mapping expressed as at least four hexdigits.
258 (L</casespec()> should be used in addition to B<charinfo()>
259 for case mappings when the calling program can cope with multiple code point
264 the block I<code> belongs to (used in C<\p{Blk=...}>).
265 See L</Blocks versus Scripts>.
270 the script I<code> belongs to.
271 See L</Blocks versus Scripts>.
275 Note that you cannot do (de)composition and casing based solely on the
276 I<decomposition>, I<combining>, I<lower>, I<upper>, and I<title> fields;
277 you will need also the L</compexcl()>, and L</casespec()> functions.
281 # NB: This function is nearly duplicated in charnames.pm
285 if ($arg =~ /^[1-9]\d*$/) {
287 } elsif ($arg =~ /^(?:[Uu]\+|0[xX])?([[:xdigit:]]+)$/) {
294 # Populated by _num. Converts real number back to input rational
295 my %real_to_rational;
297 # To store the contents of files found on disk.
309 # This function has traditionally mimicked what is in UnicodeData.txt,
310 # warts and all. This is a re-write that avoids UnicodeData.txt so that
311 # it can be removed to save disk space. Instead, this assembles
312 # information gotten by other methods that get data from various other
313 # files. It uses charnames to get the character name; and various
316 use feature 'unicode_strings';
319 my $code = _getcode($arg);
320 croak __PACKAGE__, "::charinfo: unknown code '$arg'" unless defined $code;
322 # Non-unicode implies undef.
323 return if $code > 0x10FFFF;
326 my $char = chr($code);
328 @CATEGORIES =_read_table("unicore/To/Gc.pl") unless @CATEGORIES;
329 $prop{'category'} = _search(\@CATEGORIES, 0, $#CATEGORIES, $code)
330 // $utf8::SwashInfo{'ToGc'}{'missing'};
332 return if $prop{'category'} eq 'Cn'; # Unassigned code points are undef
334 $prop{'code'} = sprintf "%04X", $code;
335 $prop{'name'} = ($char =~ /\p{Cntrl}/) ? '<control>'
336 : (charnames::viacode($code) // "");
338 $prop{'combining'} = getCombinClass($code);
340 @BIDIS =_read_table("unicore/To/Bc.pl") unless @BIDIS;
341 $prop{'bidi'} = _search(\@BIDIS, 0, $#BIDIS, $code)
342 // $utf8::SwashInfo{'ToBc'}{'missing'};
344 # For most code points, we can just read in "unicore/Decomposition.pl", as
345 # its contents are exactly what should be output. But that file doesn't
346 # contain the data for the Hangul syllable decompositions, which can be
347 # algorithmically computed, and NFD() does that, so we call NFD() for
348 # those. We can't use NFD() for everything, as it does a complete
349 # recursive decomposition, and what this function has always done is to
350 # return what's in UnicodeData.txt which doesn't show that recursiveness.
351 # Fortunately, the NFD() of the Hanguls doesn't have any recursion
353 # Having no decomposition implies an empty field; otherwise, all but
354 # "Canonical" imply a compatible decomposition, and the type is prefixed
355 # to that, as it is in UnicodeData.txt
356 if ($char =~ /\p{Block=Hangul_Syllables}/) {
357 # The code points of the decomposition are output in standard Unicode
358 # hex format, separated by blanks.
359 $prop{'decomposition'} = join " ", map { sprintf("%04X", $_)}
360 unpack "U*", NFD($char);
363 @DECOMPOSITIONS = _read_table("unicore/Decomposition.pl")
364 unless @DECOMPOSITIONS;
365 $prop{'decomposition'} = _search(\@DECOMPOSITIONS, 0, $#DECOMPOSITIONS,
369 # Can use num() to get the numeric values, if any.
370 if (! defined (my $value = num($char))) {
371 $prop{'decimal'} = $prop{'digit'} = $prop{'numeric'} = "";
375 $prop{'decimal'} = $prop{'digit'} = $prop{'numeric'} = $value;
379 # For non-decimal-digits, we have to read in the Numeric type
380 # to distinguish them. It is not just a matter of integer vs.
381 # rational, as some whole number values are not considered digits,
382 # e.g., TAMIL NUMBER TEN.
383 $prop{'decimal'} = "";
385 @NUMERIC_TYPES =_read_table("unicore/To/Nt.pl")
386 unless @NUMERIC_TYPES;
387 if ((_search(\@NUMERIC_TYPES, 0, $#NUMERIC_TYPES, $code) // "")
390 $prop{'digit'} = $prop{'numeric'} = $value;
394 $prop{'numeric'} = $real_to_rational{$value} // $value;
399 $prop{'mirrored'} = ($char =~ /\p{Bidi_Mirrored}/) ? 'Y' : 'N';
401 %UNICODE_1_NAMES =_read_table("unicore/To/Na1.pl", "use_hash") unless %UNICODE_1_NAMES;
402 $prop{'unicode10'} = $UNICODE_1_NAMES{$code} // "";
404 # This is true starting in 6.0, but, num() also requires 6.0, so
405 # don't need to test for version again here.
406 $prop{'comment'} = "";
408 %SIMPLE_UPPER = _read_table("unicore/To/Uc.pl", "use_hash")
409 unless %SIMPLE_UPPER;
410 $prop{'upper'} = $SIMPLE_UPPER{$code} // "";
412 %SIMPLE_LOWER = _read_table("unicore/To/Lc.pl", "use_hash")
413 unless %SIMPLE_LOWER;
414 $prop{'lower'} = $SIMPLE_LOWER{$code} // "";
416 %SIMPLE_TITLE = _read_table("unicore/To/Tc.pl", "use_hash")
417 unless %SIMPLE_TITLE;
418 $prop{'title'} = $SIMPLE_TITLE{$code} // "";
420 $prop{block} = charblock($code);
421 $prop{script} = charscript($code);
425 sub _search { # Binary search in a [[lo,hi,prop],[...],...] table.
426 my ($table, $lo, $hi, $code) = @_;
430 my $mid = int(($lo+$hi) / 2);
432 if ($table->[$mid]->[0] < $code) {
433 if ($table->[$mid]->[1] >= $code) {
434 return $table->[$mid]->[2];
436 _search($table, $mid + 1, $hi, $code);
438 } elsif ($table->[$mid]->[0] > $code) {
439 _search($table, $lo, $mid - 1, $code);
441 return $table->[$mid]->[2];
445 sub _read_table ($;$) {
447 # Returns the contents of the mktables generated table file located at $1
448 # in the form of either an array of arrays or a hash, depending on if the
449 # optional second parameter is true (for hash return) or not. In the case
450 # of a hash return, each key is a code point, and its corresponding value
451 # is what the table gives as the code point's corresponding value. In the
452 # case of an array return, each outer array denotes a range with [0] the
453 # start point of that range; [1] the end point; and [2] the value that
454 # every code point in the range has. The hash return is useful for fast
455 # lookup when the table contains only single code point ranges. The array
456 # return takes much less memory when there are large ranges.
458 # This function has the side effect of setting
459 # $utf8::SwashInfo{$property}{'format'} to be the mktables format of the
461 # $utf8::SwashInfo{$property}{'missing'} to be the value for all entries
462 # not listed in the table.
463 # where $property is the Unicode property name, preceded by 'To' for map
464 # properties., e.g., 'ToSc'.
466 # Table entries look like one of:
467 # 0000 0040 Common # [65]
471 my $return_hash = shift;
472 $return_hash = 0 unless defined $return_hash;
477 for (split /^/m, do $table) {
478 my ($start, $end, $value) = / ^ (.+?) \t (.*?) \t (.+?)
479 \s* ( \# .* )? # Optional comment
481 my $decimal_start = hex $start;
482 my $decimal_end = ($end eq "") ? $decimal_start : hex $end;
484 foreach my $i ($decimal_start .. $decimal_end) {
485 $return{$i} = $value;
489 $return[-1][1] == $decimal_start - 1
490 && $return[-1][2] eq $value)
492 # If this is merely extending the previous range, do just that.
493 $return[-1]->[1] = $decimal_end;
496 push @return, [ $decimal_start, $decimal_end, $value ];
499 return ($return_hash) ? %return : @return;
503 my ($range, $arg) = @_;
504 my $code = _getcode($arg);
505 croak __PACKAGE__, "::charinrange: unknown code '$arg'"
506 unless defined $code;
507 _search($range, 0, $#$range, $code);
510 =head2 B<charblock()>
512 use Unicode::UCD 'charblock';
514 my $charblock = charblock(0x41);
515 my $charblock = charblock(1234);
516 my $charblock = charblock(0x263a);
517 my $charblock = charblock("U+263a");
519 my $range = charblock('Armenian');
521 With a L</code point argument> charblock() returns the I<block> the code point
522 belongs to, e.g. C<Basic Latin>. The old-style block name is returned (see
523 L</Old-style versus new-style block names>).
524 If the code point is unassigned, this returns the block it would belong to if
527 See also L</Blocks versus Scripts>.
529 If supplied with an argument that can't be a code point, charblock() tries to
530 do the opposite and interpret the argument as an old-style block name. The
532 is a I<range set> with one range: an anonymous list with a single element that
533 consists of another anonymous list whose first element is the first code point
534 in the block, and whose second (and final) element is the final code point in
535 the block. (The extra list consisting of just one element is so that the same
536 program logic can be used to handle both this return, and the return from
537 L</charscript()> which can have multiple ranges.) You can test whether a code
538 point is in a range using the L</charinrange()> function. If the argument is
539 not a known block, C<undef> is returned.
548 # Can't read from the mktables table because it loses the hyphens in the
551 if (openunicode(\$BLOCKSFH, "Blocks.txt")) {
554 while (<$BLOCKSFH>) {
555 if (/^([0-9A-F]+)\.\.([0-9A-F]+);\s+(.+)/) {
556 my ($lo, $hi) = (hex($1), hex($2));
557 my $subrange = [ $lo, $hi, $3 ];
558 push @BLOCKS, $subrange;
559 push @{$BLOCKS{$3}}, $subrange;
570 _charblocks() unless @BLOCKS;
572 my $code = _getcode($arg);
575 my $result = _search(\@BLOCKS, 0, $#BLOCKS, $code);
576 return $result if defined $result;
579 elsif (exists $BLOCKS{$arg}) {
580 return dclone $BLOCKS{$arg};
584 =head2 B<charscript()>
586 use Unicode::UCD 'charscript';
588 my $charscript = charscript(0x41);
589 my $charscript = charscript(1234);
590 my $charscript = charscript("U+263a");
592 my $range = charscript('Thai');
594 With a L</code point argument> charscript() returns the I<script> the
595 code point belongs to, e.g. C<Latin>, C<Greek>, C<Han>.
596 If the code point is unassigned, it returns C<"Unknown">.
598 If supplied with an argument that can't be a code point, charscript() tries
599 to do the opposite and interpret the argument as a script name. The
600 return value is a I<range set>: an anonymous list of lists that contain
601 I<start-of-range>, I<end-of-range> code point pairs. You can test whether a
602 code point is in a range set using the L</charinrange()> function. If the
603 argument is not a known script, C<undef> is returned.
605 See also L</Blocks versus Scripts>.
613 @SCRIPTS =_read_table("unicore/To/Sc.pl") unless @SCRIPTS;
614 foreach my $entry (@SCRIPTS) {
615 $entry->[2] =~ s/(_\w)/\L$1/g; # Preserve old-style casing
616 push @{$SCRIPTS{$entry->[2]}}, $entry;
623 _charscripts() unless @SCRIPTS;
625 my $code = _getcode($arg);
628 my $result = _search(\@SCRIPTS, 0, $#SCRIPTS, $code);
629 return $result if defined $result;
630 return $utf8::SwashInfo{'ToSc'}{'missing'};
631 } elsif (exists $SCRIPTS{$arg}) {
632 return dclone $SCRIPTS{$arg};
638 =head2 B<charblocks()>
640 use Unicode::UCD 'charblocks';
642 my $charblocks = charblocks();
644 charblocks() returns a reference to a hash with the known block names
645 as the keys, and the code point ranges (see L</charblock()>) as the values.
647 The names are in the old-style (see L</Old-style versus new-style block
650 L<prop_invmap("block")|/prop_invmap()> can be used to get this same data in a
651 different type of data structure.
653 See also L</Blocks versus Scripts>.
658 _charblocks() unless %BLOCKS;
659 return dclone \%BLOCKS;
662 =head2 B<charscripts()>
664 use Unicode::UCD 'charscripts';
666 my $charscripts = charscripts();
668 charscripts() returns a reference to a hash with the known script
669 names as the keys, and the code point ranges (see L</charscript()>) as
672 L<prop_invmap("script")|/prop_invmap()> can be used to get this same data in a
673 different type of data structure.
675 See also L</Blocks versus Scripts>.
680 _charscripts() unless %SCRIPTS;
681 return dclone \%SCRIPTS;
684 =head2 B<charinrange()>
686 In addition to using the C<\p{Blk=...}> and C<\P{Blk=...}> constructs, you
687 can also test whether a code point is in the I<range> as returned by
688 L</charblock()> and L</charscript()> or as the values of the hash returned
689 by L</charblocks()> and L</charscripts()> by using charinrange():
691 use Unicode::UCD qw(charscript charinrange);
693 $range = charscript('Hiragana');
694 print "looks like hiragana\n" if charinrange($range, $codepoint);
698 my %GENERAL_CATEGORIES =
701 'LC' => 'CasedLetter',
702 'Lu' => 'UppercaseLetter',
703 'Ll' => 'LowercaseLetter',
704 'Lt' => 'TitlecaseLetter',
705 'Lm' => 'ModifierLetter',
706 'Lo' => 'OtherLetter',
708 'Mn' => 'NonspacingMark',
709 'Mc' => 'SpacingMark',
710 'Me' => 'EnclosingMark',
712 'Nd' => 'DecimalNumber',
713 'Nl' => 'LetterNumber',
714 'No' => 'OtherNumber',
715 'P' => 'Punctuation',
716 'Pc' => 'ConnectorPunctuation',
717 'Pd' => 'DashPunctuation',
718 'Ps' => 'OpenPunctuation',
719 'Pe' => 'ClosePunctuation',
720 'Pi' => 'InitialPunctuation',
721 'Pf' => 'FinalPunctuation',
722 'Po' => 'OtherPunctuation',
724 'Sm' => 'MathSymbol',
725 'Sc' => 'CurrencySymbol',
726 'Sk' => 'ModifierSymbol',
727 'So' => 'OtherSymbol',
729 'Zs' => 'SpaceSeparator',
730 'Zl' => 'LineSeparator',
731 'Zp' => 'ParagraphSeparator',
736 'Co' => 'PrivateUse',
737 'Cn' => 'Unassigned',
740 sub general_categories {
741 return dclone \%GENERAL_CATEGORIES;
744 =head2 B<general_categories()>
746 use Unicode::UCD 'general_categories';
748 my $categories = general_categories();
750 This returns a reference to a hash which has short
751 general category names (such as C<Lu>, C<Nd>, C<Zs>, C<S>) as keys and long
752 names (such as C<UppercaseLetter>, C<DecimalNumber>, C<SpaceSeparator>,
753 C<Symbol>) as values. The hash is reversible in case you need to go
754 from the long names to the short names. The general category is the
756 L</charinfo()> under the C<category> key.
758 The L</prop_value_aliases()> function can be used to get all the synonyms of
765 'L' => 'Left-to-Right',
766 'LRE' => 'Left-to-Right Embedding',
767 'LRO' => 'Left-to-Right Override',
768 'R' => 'Right-to-Left',
769 'AL' => 'Right-to-Left Arabic',
770 'RLE' => 'Right-to-Left Embedding',
771 'RLO' => 'Right-to-Left Override',
772 'PDF' => 'Pop Directional Format',
773 'EN' => 'European Number',
774 'ES' => 'European Number Separator',
775 'ET' => 'European Number Terminator',
776 'AN' => 'Arabic Number',
777 'CS' => 'Common Number Separator',
778 'NSM' => 'Non-Spacing Mark',
779 'BN' => 'Boundary Neutral',
780 'B' => 'Paragraph Separator',
781 'S' => 'Segment Separator',
782 'WS' => 'Whitespace',
783 'ON' => 'Other Neutrals',
786 =head2 B<bidi_types()>
788 use Unicode::UCD 'bidi_types';
790 my $categories = bidi_types();
792 This returns a reference to a hash which has the short
793 bidi (bidirectional) type names (such as C<L>, C<R>) as keys and long
794 names (such as C<Left-to-Right>, C<Right-to-Left>) as values. The
795 hash is reversible in case you need to go from the long names to the
796 short names. The bidi type is the one returned from
798 under the C<bidi> key. For the exact meaning of the various bidi classes
799 the Unicode TR9 is recommended reading:
800 L<http://www.unicode.org/reports/tr9/>
801 (as of Unicode 5.0.0)
803 The L</prop_value_aliases()> function can be used to get all the synonyms of
809 return dclone \%BIDI_TYPES;
814 use Unicode::UCD 'compexcl';
816 my $compexcl = compexcl(0x09dc);
818 This routine is included for backwards compatibility, but as of Perl 5.12, for
819 most purposes it is probably more convenient to use one of the following
822 my $compexcl = chr(0x09dc) =~ /\p{Comp_Ex};
823 my $compexcl = chr(0x09dc) =~ /\p{Full_Composition_Exclusion};
827 my $compexcl = chr(0x09dc) =~ /\p{CE};
828 my $compexcl = chr(0x09dc) =~ /\p{Composition_Exclusion};
830 The first two forms return B<true> if the L</code point argument> should not
831 be produced by composition normalization. For the final two forms to return
832 B<true>, it is additionally required that this fact not otherwise be
833 determinable from the Unicode data base.
835 This routine behaves identically to the final two forms. That is,
836 it does not return B<true> if the code point has a decomposition
837 consisting of another single code point, nor if its decomposition starts
838 with a code point whose combining class is non-zero. Code points that meet
839 either of these conditions should also not be produced by composition
840 normalization, which is probably why you should use the
841 C<Full_Composition_Exclusion> property instead, as shown above.
843 The routine returns B<false> otherwise.
849 my $code = _getcode($arg);
850 croak __PACKAGE__, "::compexcl: unknown code '$arg'"
851 unless defined $code;
853 no warnings "non_unicode"; # So works on non-Unicode code points
854 return chr($code) =~ /\p{Composition_Exclusion}/;
859 use Unicode::UCD 'casefold';
861 my $casefold = casefold(0xDF);
862 if (defined $casefold) {
863 my @full_fold_hex = split / /, $casefold->{'full'};
864 my $full_fold_string =
865 join "", map {chr(hex($_))} @full_fold_hex;
866 my @turkic_fold_hex =
867 split / /, ($casefold->{'turkic'} ne "")
868 ? $casefold->{'turkic'}
869 : $casefold->{'full'};
870 my $turkic_fold_string =
871 join "", map {chr(hex($_))} @turkic_fold_hex;
873 if (defined $casefold && $casefold->{'simple'} ne "") {
874 my $simple_fold_hex = $casefold->{'simple'};
875 my $simple_fold_string = chr(hex($simple_fold_hex));
878 This returns the (almost) locale-independent case folding of the
879 character specified by the L</code point argument>.
881 If there is no case folding for that code point, C<undef> is returned.
883 If there is a case folding for that code point, a reference to a hash
884 with the following fields is returned:
890 the input L</code point argument> expressed in hexadecimal, with leading zeros
891 added if necessary to make it contain at least four hexdigits
895 one or more codes (separated by spaces) that, taken in order, give the
896 code points for the case folding for I<code>.
897 Each has at least four hexdigits.
901 is empty, or is exactly one code with at least four hexdigits which can be used
902 as an alternative case folding when the calling program cannot cope with the
903 fold being a sequence of multiple code points. If I<full> is just one code
904 point, then I<simple> equals I<full>. If there is no single code point folding
905 defined for I<code>, then I<simple> is the empty string. Otherwise, it is an
906 inferior, but still better-than-nothing alternative folding to I<full>.
910 is the same as I<simple> if I<simple> is not empty, and it is the same as I<full>
911 otherwise. It can be considered to be the simplest possible folding for
912 I<code>. It is defined primarily for backwards compatibility.
916 is C<C> (for C<common>) if the best possible fold is a single code point
917 (I<simple> equals I<full> equals I<mapping>). It is C<S> if there are distinct
918 folds, I<simple> and I<full> (I<mapping> equals I<simple>). And it is C<F> if
919 there is only a I<full> fold (I<mapping> equals I<full>; I<simple> is empty).
921 describes the contents of I<mapping>. It is defined primarily for backwards
924 On versions 3.1 and earlier of Unicode, I<status> can also be
925 C<I> which is the same as C<C> but is a special case for dotted uppercase I and
930 =item B<*> If you use this C<I> mapping
932 the result is case-insensitive,
933 but dotless and dotted I's are not distinguished
935 =item B<*> If you exclude this C<I> mapping
937 the result is not fully case-insensitive, but
938 dotless and dotted I's are distinguished
944 contains any special folding for Turkic languages. For versions of Unicode
945 starting with 3.2, this field is empty unless I<code> has a different folding
946 in Turkic languages, in which case it is one or more codes (separated by
947 spaces) that, taken in order, give the code points for the case folding for
948 I<code> in those languages.
949 Each code has at least four hexdigits.
950 Note that this folding does not maintain canonical equivalence without
951 additional processing.
953 For versions of Unicode 3.1 and earlier, this field is empty unless there is a
954 special folding for Turkic languages, in which case I<status> is C<I>, and
955 I<mapping>, I<full>, I<simple>, and I<turkic> are all equal.
959 Programs that want complete generality and the best folding results should use
960 the folding contained in the I<full> field. But note that the fold for some
961 code points will be a sequence of multiple code points.
963 Programs that can't cope with the fold mapping being multiple code points can
964 use the folding contained in the I<simple> field, with the loss of some
965 generality. In Unicode 5.1, about 7% of the defined foldings have no single
968 The I<mapping> and I<status> fields are provided for backwards compatibility for
969 existing programs. They contain the same values as in previous versions of
972 Locale is not completely independent. The I<turkic> field contains results to
973 use when the locale is a Turkic language.
975 For more information about case mappings see
976 L<http://www.unicode.org/unicode/reports/tr21>
984 if (openunicode(\$CASEFOLDFH, "CaseFolding.txt")) {
987 while (<$CASEFOLDFH>) {
988 if (/^([0-9A-F]+); ([CFIST]); ([0-9A-F]+(?: [0-9A-F]+)*);/) {
990 $CASEFOLD{$code}{'code'} = $1;
991 $CASEFOLD{$code}{'turkic'} = "" unless
992 defined $CASEFOLD{$code}{'turkic'};
993 if ($2 eq 'C' || $2 eq 'I') { # 'I' is only on 3.1 and
995 # Both entries there (I
996 # only checked 3.1) are
1000 # codepoints, so treat
1001 # as if C, but override
1002 # the turkic one for
1004 $CASEFOLD{$code}{'status'} = $2;
1005 $CASEFOLD{$code}{'full'} = $CASEFOLD{$code}{'simple'} =
1006 $CASEFOLD{$code}{'mapping'} = $3;
1007 $CASEFOLD{$code}{'turkic'} = $3 if $2 eq 'I';
1008 } elsif ($2 eq 'F') {
1009 $CASEFOLD{$code}{'full'} = $3;
1010 unless (defined $CASEFOLD{$code}{'simple'}) {
1011 $CASEFOLD{$code}{'simple'} = "";
1012 $CASEFOLD{$code}{'mapping'} = $3;
1013 $CASEFOLD{$code}{'status'} = $2;
1015 } elsif ($2 eq 'S') {
1018 # There can't be a simple without a full, and simple
1019 # overrides all but full
1021 $CASEFOLD{$code}{'simple'} = $3;
1022 $CASEFOLD{$code}{'mapping'} = $3;
1023 $CASEFOLD{$code}{'status'} = $2;
1024 } elsif ($2 eq 'T') {
1025 $CASEFOLD{$code}{'turkic'} = $3;
1026 } # else can't happen because only [CIFST] are possible
1036 my $code = _getcode($arg);
1037 croak __PACKAGE__, "::casefold: unknown code '$arg'"
1038 unless defined $code;
1040 _casefold() unless %CASEFOLD;
1042 return $CASEFOLD{$code};
1045 =head2 B<casespec()>
1047 use Unicode::UCD 'casespec';
1049 my $casespec = casespec(0xFB00);
1051 This returns the potentially locale-dependent case mappings of the L</code point
1052 argument>. The mappings may be longer than a single code point (which the basic
1053 Unicode case mappings as returned by L</charinfo()> never are).
1055 If there are no case mappings for the L</code point argument>, or if all three
1056 possible mappings (I<lower>, I<title> and I<upper>) result in single code
1057 points and are locale independent and unconditional, C<undef> is returned
1058 (which means that the case mappings, if any, for the code point are those
1059 returned by L</charinfo()>).
1061 Otherwise, a reference to a hash giving the mappings (or a reference to a hash
1062 of such hashes, explained below) is returned with the following keys and their
1065 The keys in the bottom layer hash with the meanings of their values are:
1071 the input L</code point argument> expressed in hexadecimal, with leading zeros
1072 added if necessary to make it contain at least four hexdigits
1076 one or more codes (separated by spaces) that, taken in order, give the
1077 code points for the lower case of I<code>.
1078 Each has at least four hexdigits.
1082 one or more codes (separated by spaces) that, taken in order, give the
1083 code points for the title case of I<code>.
1084 Each has at least four hexdigits.
1088 one or more codes (separated by spaces) that, taken in order, give the
1089 code points for the upper case of I<code>.
1090 Each has at least four hexdigits.
1094 the conditions for the mappings to be valid.
1095 If C<undef>, the mappings are always valid.
1096 When defined, this field is a list of conditions,
1097 all of which must be true for the mappings to be valid.
1098 The list consists of one or more
1099 I<locales> (see below)
1100 and/or I<contexts> (explained in the next paragraph),
1101 separated by spaces.
1102 (Other than as used to separate elements, spaces are to be ignored.)
1103 Case distinctions in the condition list are not significant.
1104 Conditions preceded by "NON_" represent the negation of the condition.
1106 A I<context> is one of those defined in the Unicode standard.
1107 For Unicode 5.1, they are defined in Section 3.13 C<Default Case Operations>
1109 L<http://www.unicode.org/versions/Unicode5.1.0/>.
1110 These are for context-sensitive casing.
1114 The hash described above is returned for locale-independent casing, where
1115 at least one of the mappings has length longer than one. If C<undef> is
1116 returned, the code point may have mappings, but if so, all are length one,
1117 and are returned by L</charinfo()>.
1118 Note that when this function does return a value, it will be for the complete
1119 set of mappings for a code point, even those whose length is one.
1121 If there are additional casing rules that apply only in certain locales,
1122 an additional key for each will be defined in the returned hash. Each such key
1123 will be its locale name, defined as a 2-letter ISO 3166 country code, possibly
1124 followed by a "_" and a 2-letter ISO language code (possibly followed by a "_"
1125 and a variant code). You can find the lists of all possible locales, see
1126 L<Locale::Country> and L<Locale::Language>.
1127 (In Unicode 6.0, the only locales returned by this function
1128 are C<lt>, C<tr>, and C<az>.)
1130 Each locale key is a reference to a hash that has the form above, and gives
1131 the casing rules for that particular locale, which take precedence over the
1132 locale-independent ones when in that locale.
1134 If the only casing for a code point is locale-dependent, then the returned
1135 hash will not have any of the base keys, like C<code>, C<upper>, etc., but
1136 will contain only locale keys.
1138 For more information about case mappings see
1139 L<http://www.unicode.org/unicode/reports/tr21/>
1146 unless (%CASESPEC) {
1147 if (openunicode(\$CASESPECFH, "SpecialCasing.txt")) {
1150 while (<$CASESPECFH>) {
1151 if (/^([0-9A-F]+); ([0-9A-F]+(?: [0-9A-F]+)*)?; ([0-9A-F]+(?: [0-9A-F]+)*)?; ([0-9A-F]+(?: [0-9A-F]+)*)?; (\w+(?: \w+)*)?/) {
1152 my ($hexcode, $lower, $title, $upper, $condition) =
1153 ($1, $2, $3, $4, $5);
1154 my $code = hex($hexcode);
1155 if (exists $CASESPEC{$code}) {
1156 if (exists $CASESPEC{$code}->{code}) {
1161 @{$CASESPEC{$code}}{qw(lower
1165 if (defined $oldcondition) {
1167 ($oldcondition =~ /^([a-z][a-z](?:_\S+)?)/);
1168 delete $CASESPEC{$code};
1169 $CASESPEC{$code}->{$oldlocale} =
1174 condition => $oldcondition };
1178 ($condition =~ /^([a-z][a-z](?:_\S+)?)/);
1179 $CASESPEC{$code}->{$locale} =
1184 condition => $condition };
1191 condition => $condition };
1202 my $code = _getcode($arg);
1203 croak __PACKAGE__, "::casespec: unknown code '$arg'"
1204 unless defined $code;
1206 _casespec() unless %CASESPEC;
1208 return ref $CASESPEC{$code} ? dclone $CASESPEC{$code} : $CASESPEC{$code};
1211 =head2 B<namedseq()>
1213 use Unicode::UCD 'namedseq';
1215 my $namedseq = namedseq("KATAKANA LETTER AINU P");
1216 my @namedseq = namedseq("KATAKANA LETTER AINU P");
1217 my %namedseq = namedseq();
1219 If used with a single argument in a scalar context, returns the string
1220 consisting of the code points of the named sequence, or C<undef> if no
1221 named sequence by that name exists. If used with a single argument in
1222 a list context, it returns the list of the ordinals of the code points. If used
1224 arguments in a list context, returns a hash with the names of the
1225 named sequences as the keys and the named sequences as strings as
1226 the values. Otherwise, it returns C<undef> or an empty list depending
1229 This function only operates on officially approved (not provisional) named
1232 Note that as of Perl 5.14, C<\N{KATAKANA LETTER AINU P}> will insert the named
1233 sequence into double-quoted strings, and C<charnames::string_vianame("KATAKANA
1234 LETTER AINU P")> will return the same string this function does, but will also
1235 operate on character names that aren't named sequences, without you having to
1236 know which are which. See L<charnames>.
1243 unless (%NAMEDSEQ) {
1244 if (openunicode(\$NAMEDSEQFH, "Name.pl")) {
1247 while (<$NAMEDSEQFH>) {
1248 if (/^ [0-9A-F]+ \ /x) {
1250 my ($sequence, $name) = split /\t/;
1251 my @s = map { chr(hex($_)) } split(' ', $sequence);
1252 $NAMEDSEQ{$name} = join("", @s);
1262 # Use charnames::string_vianame() which now returns this information,
1263 # unless the caller wants the hash returned, in which case we read it in,
1264 # and thereafter use it instead of calling charnames, as it is faster.
1266 my $wantarray = wantarray();
1267 if (defined $wantarray) {
1270 _namedseq() unless %NAMEDSEQ;
1275 $s = $NAMEDSEQ{ $_[0] };
1278 $s = charnames::string_vianame($_[0]);
1280 return defined $s ? map { ord($_) } split('', $s) : ();
1283 return $NAMEDSEQ{ $_[0] } if %NAMEDSEQ;
1284 return charnames::string_vianame($_[0]);
1294 # Unicode 6.0 instituted the rule that only digits in a consecutive
1295 # block of 10 would be considered decimal digits. Before that, the only
1296 # problematic code point that I'm (khw) aware of is U+019DA, NEW TAI LUE
1297 # THAM DIGIT ONE, which is an alternate form of U+019D1, NEW TAI LUE DIGIT
1298 # ONE. The code could be modified to handle that, but not bothering, as
1299 # in TUS 6.0, U+19DA was changed to Nt=Di.
1300 if ((pack "C*", split /\./, UnicodeVersion()) lt 6.0.0) {
1301 croak __PACKAGE__, "::num requires Unicode 6.0 or greater"
1303 my @numbers = _read_table("unicore/To/Nv.pl");
1304 foreach my $entry (@numbers) {
1305 my ($start, $end, $value) = @$entry;
1307 # If value contains a slash, convert to decimal, add a reverse hash
1309 if ((my @rational = split /\//, $value) == 2) {
1310 my $real = $rational[0] / $rational[1];
1311 $real_to_rational{$real} = $value;
1315 for my $i ($start .. $end) {
1316 $NUMERIC{$i} = $value;
1320 # Decided unsafe to use these that aren't officially part of the Unicode
1323 #my $pi = acos(-1.0);
1324 #$NUMERIC{0x03C0} = $pi;
1326 # Euler's constant, not to be confused with Euler's number
1327 #$NUMERIC{0x2107} = 0.57721566490153286060651209008240243104215933593992;
1330 #$NUMERIC{0x212F} = 2.7182818284590452353602874713526624977572;
1339 use Unicode::UCD 'num';
1341 my $val = num("123");
1342 my $one_quarter = num("\N{VULGAR FRACTION 1/4}");
1344 C<num> returns the numeric value of the input Unicode string; or C<undef> if it
1345 doesn't think the entire string has a completely valid, safe numeric value.
1347 If the string is just one character in length, the Unicode numeric value
1348 is returned if it has one, or C<undef> otherwise. Note that this need
1349 not be a whole number. C<num("\N{TIBETAN DIGIT HALF ZERO}")>, for
1350 example returns -0.5.
1354 #A few characters to which Unicode doesn't officially
1355 #assign a numeric value are considered numeric by C<num>.
1358 # EULER CONSTANT 0.5772... (this is NOT Euler's number)
1359 # SCRIPT SMALL E 2.71828... (this IS Euler's number)
1360 # GREEK SMALL LETTER PI 3.14159...
1364 If the string is more than one character, C<undef> is returned unless
1365 all its characters are decimal digits (that is, they would match C<\d+>),
1366 from the same script. For example if you have an ASCII '0' and a Bengali
1367 '3', mixed together, they aren't considered a valid number, and C<undef>
1368 is returned. A further restriction is that the digits all have to be of
1369 the same form. A half-width digit mixed with a full-width one will
1370 return C<undef>. The Arabic script has two sets of digits; C<num> will
1371 return C<undef> unless all the digits in the string come from the same
1374 C<num> errs on the side of safety, and there may be valid strings of
1375 decimal digits that it doesn't recognize. Note that Unicode defines
1376 a number of "digit" characters that aren't "decimal digit" characters.
1377 "Decimal digits" have the property that they have a positional value, i.e.,
1378 there is a units position, a 10's position, a 100's, etc, AND they are
1379 arranged in Unicode in blocks of 10 contiguous code points. The Chinese
1380 digits, for example, are not in such a contiguous block, and so Unicode
1381 doesn't view them as decimal digits, but merely digits, and so C<\d> will not
1382 match them. A single-character string containing one of these digits will
1383 have its decimal value returned by C<num>, but any longer string containing
1384 only these digits will return C<undef>.
1386 Strings of multiple sub- and superscripts are not recognized as numbers. You
1387 can use either of the compatibility decompositions in Unicode::Normalize to
1388 change these into digits, and then call C<num> on the result.
1392 # To handle sub, superscripts, this could if called in list context,
1393 # consider those, and return the <decomposition> type in the second
1399 _numeric unless %NUMERIC;
1401 my $length = length($string);
1402 return $NUMERIC{ord($string)} if $length == 1;
1403 return if $string =~ /\D/;
1404 my $first_ord = ord(substr($string, 0, 1));
1405 my $value = $NUMERIC{$first_ord};
1406 my $zero_ord = $first_ord - $value;
1408 for my $i (1 .. $length -1) {
1409 my $ord = ord(substr($string, $i, 1));
1410 my $digit = $ord - $zero_ord;
1411 return unless $digit >= 0 && $digit <= 9;
1412 $value = $value * 10 + $digit;
1419 =head2 B<prop_aliases()>
1421 use Unicode::UCD 'prop_aliases';
1423 my ($short_name, $full_name, @other_names) = prop_aliases("space");
1424 my $same_full_name = prop_aliases("Space"); # Scalar context
1425 my ($same_short_name) = prop_aliases("Space"); # gets 0th element
1426 print "The full name is $full_name\n";
1427 print "The short name is $short_name\n";
1428 print "The other aliases are: ", join(", ", @other_names), "\n";
1431 The full name is White_Space
1432 The short name is WSpace
1433 The other aliases are: Space
1435 Most Unicode properties have several synonymous names. Typically, there is at
1436 least a short name, convenient to type, and a long name that more fully
1437 describes the property, and hence is more easily understood.
1439 If you know one name for a Unicode property, you can use C<prop_aliases> to find
1440 either the long name (when called in scalar context), or a list of all of the
1441 names, somewhat ordered so that the short name is in the 0th element, the long
1442 name in the next element, and any other synonyms are in the remaining
1443 elements, in no particular order.
1445 The long name is returned in a form nicely capitalized, suitable for printing.
1447 The input parameter name is loosely matched, which means that white space,
1448 hyphens, and underscores are ignored (except for the trailing underscore in
1449 the old_form grandfathered-in C<"L_">, which is better written as C<"LC">, and
1450 both of which mean C<General_Category=Cased Letter>).
1452 If the name is unknown, C<undef> is returned (or an empty list in list
1453 context). Note that Perl typically recognizes property names in regular
1454 expressions with an optional C<"Is_>" (with or without the underscore)
1455 prefixed to them, such as C<\p{isgc=punct}>. This function does not recognize
1456 those in the input, returning C<undef>. Nor are they included in the output
1457 as possible synonyms.
1459 C<prop_aliases> does know about the Perl extensions to Unicode properties,
1460 such as C<Any> and C<XPosixAlpha>, and the single form equivalents to Unicode
1461 properties such as C<XDigit>, C<Greek>, C<In_Greek>, and C<Is_Greek>. The
1462 final example demonstrates that the C<"Is_"> prefix is recognized for these
1463 extensions; it is needed to resolve ambiguities. For example,
1464 C<prop_aliases('lc')> returns the list C<(lc, Lowercase_Mapping)>, but
1465 C<prop_aliases('islc')> returns C<(Is_LC, Cased_Letter)>. This is
1466 because C<islc> is a Perl extension which is short for
1467 C<General_Category=Cased Letter>. The lists returned for the Perl extensions
1468 will not include the C<"Is_"> prefix (whether or not the input had it) unless
1469 needed to resolve ambiguities, as shown in the C<"islc"> example, where the
1470 returned list had one element containing C<"Is_">, and the other without.
1472 It is also possible for the reverse to happen: C<prop_aliases('isc')> returns
1473 the list C<(isc, ISO_Comment)>; whereas C<prop_aliases('c')> returns
1474 C<(C, Other)> (the latter being a Perl extension meaning
1475 C<General_Category=Other>.
1476 L<perluniprops/Properties accessible through Unicode::UCD> lists the available
1477 forms, including which ones are discouraged from use.
1479 Those discouraged forms are accepted as input to C<prop_aliases>, but are not
1480 returned in the lists. C<prop_aliases('isL&')> and C<prop_aliases('isL_')>,
1481 which are old synonyms for C<"Is_LC"> and should not be used in new code, are
1482 examples of this. These both return C<(Is_LC, Cased_Letter)>. Thus this
1483 function allows you to take a discourarged form, and find its acceptable
1484 alternatives. The same goes with single-form Block property equivalences.
1485 Only the forms that begin with C<"In_"> are not discouraged; if you pass
1486 C<prop_aliases> a discouraged form, you will get back the equivalent ones that
1487 begin with C<"In_">. It will otherwise look like a new-style block name (see.
1488 L</Old-style versus new-style block names>).
1490 C<prop_aliases> does not know about any user-defined properties, and will
1491 return C<undef> if called with one of those. Likewise for Perl internal
1492 properties, with the exception of "Perl_Decimal_Digit" which it does know
1493 about (and which is documented below in L</prop_invmap()>).
1497 # It may be that there are use cases where the discouraged forms should be
1498 # returned. If that comes up, an optional boolean second parameter to the
1499 # function could be created, for example.
1501 # These are created by mktables for this routine and stored in unicore/UCD.pl
1502 # where their structures are described.
1503 our %string_property_loose_to_name;
1504 our %ambiguous_names;
1505 our %loose_perlprop_to_name;
1508 sub prop_aliases ($) {
1510 return unless defined $prop;
1512 require "unicore/UCD.pl";
1513 require "unicore/Heavy.pl";
1514 require "utf8_heavy.pl";
1516 # The property name may be loosely or strictly matched; we don't know yet.
1517 # But both types use lower-case.
1520 # It is loosely matched if its lower case isn't known to be strict.
1522 if (! exists $utf8::stricter_to_file_of{$prop}) {
1523 my $loose = utf8::_loose_name($prop);
1525 # There is a hash that converts from any loose name to its standard
1526 # form, mapping all synonyms for a name to one name that can be used
1527 # as a key into another hash. The whole concept is for memory
1528 # savings, as the second hash doesn't have to have all the
1529 # combinations. Actually, there are two hashes that do the
1530 # converstion. One is used in utf8_heavy.pl (stored in Heavy.pl) for
1531 # looking up properties matchable in regexes. This function needs to
1532 # access string properties, which aren't available in regexes, so a
1533 # second conversion hash is made for them (stored in UCD.pl). Look in
1534 # the string one now, as the rest can have an optional 'is' prefix,
1535 # which these don't.
1536 if (exists $string_property_loose_to_name{$loose}) {
1538 # Convert to its standard loose name.
1539 $prop = $string_property_loose_to_name{$loose};
1542 my $retrying = 0; # bool. ? Has an initial 'is' been stripped
1544 if (exists $utf8::loose_property_name_of{$loose}
1546 || ! exists $ambiguous_names{$loose}))
1548 # Found an entry giving the standard form. We don't get here
1549 # (in the test above) when we've stripped off an
1550 # 'is' and the result is an ambiguous name. That is because
1551 # these are official Unicode properties (though Perl can have
1552 # an optional 'is' prefix meaning the official property), and
1553 # all ambiguous cases involve a Perl single-form extension
1554 # for the gc, script, or block properties, and the stripped
1555 # 'is' means that they mean one of those, and not one of
1557 $prop = $utf8::loose_property_name_of{$loose};
1559 elsif (exists $loose_perlprop_to_name{$loose}) {
1561 # This hash is specifically for this function to list Perl
1562 # extensions that aren't in the earlier hashes. If there is
1563 # only one element, the short and long names are identical.
1564 # Otherwise the form is already in the same form as
1565 # %prop_aliases, which is handled at the end of the function.
1566 $list_ref = $loose_perlprop_to_name{$loose};
1567 if (@$list_ref == 1) {
1568 my @list = ($list_ref->[0], $list_ref->[0]);
1572 elsif (! exists $utf8::loose_to_file_of{$loose}) {
1574 # loose_to_file_of is a complete list of loose names. If not
1575 # there, the input is unknown.
1580 # Here we found the name but not its aliases, so it has to
1581 # exist. This means it must be one of the Perl single-form
1582 # extensions. First see if it is for a property-value
1583 # combination in one of the following properties.
1585 foreach my $property ("gc", "script") {
1586 @list = prop_value_aliases($property, $loose);
1591 # Here, it is one of those property-value combination
1592 # single-form synonyms. There are ambiguities with some
1593 # of these. Check against the list for these, and adjust
1595 for my $i (0 .. @list -1) {
1596 if (exists $ambiguous_names
1597 {utf8::_loose_name(lc $list[$i])})
1599 # The ambiguity is resolved by toggling whether or
1600 # not it has an 'is' prefix
1601 $list[$i] =~ s/^Is_// or $list[$i] =~ s/^/Is_/;
1607 # Here, it wasn't one of the gc or script single-form
1608 # extensions. It could be a block property single-form
1609 # extension. An 'in' prefix definitely means that, and should
1610 # be looked up without the prefix. However, starting in
1611 # Unicode 6.1, we have to special case 'indic...', as there
1612 # is a property that begins with that name. We shouldn't
1613 # strip the 'in' from that. I'm (khw) generalizing this to
1614 # 'indic' instead of the single property, because I suspect
1615 # that others of this class may come along in the future.
1616 # However, this could backfire and a block created whose name
1617 # begins with 'dic...', and we would want to strip the 'in'.
1618 # At which point this would have to be tweaked.
1619 my $began_with_in = $loose =~ s/^in(?!dic)//;
1620 @list = prop_value_aliases("block", $loose);
1622 map { $_ =~ s/^/In_/ } @list;
1626 # Here still haven't found it. The last opportunity for it
1627 # being valid is only if it began with 'is'. We retry without
1628 # the 'is', setting a flag to that effect so that we don't
1629 # accept things that begin with 'isis...'
1630 if (! $retrying && ! $began_with_in && $loose =~ s/^is//) {
1635 # Here, didn't find it. Since it was in %loose_to_file_of, we
1636 # should have been able to find it.
1637 carp __PACKAGE__, "::prop_aliases: Unexpectedly could not find '$prop'. Send bug report to perlbug\@perl.org";
1644 # Here, we have set $prop to a standard form name of the input. Look
1645 # it up in the structure created by mktables for this purpose, which
1646 # contains both strict and loosely matched properties. Avoid
1648 $list_ref = $prop_aliases{$prop} if exists $prop_aliases{$prop};
1649 return unless $list_ref;
1652 # The full name is in element 1.
1653 return $list_ref->[1] unless wantarray;
1655 return @{dclone $list_ref};
1660 =head2 B<prop_value_aliases()>
1662 use Unicode::UCD 'prop_value_aliases';
1664 my ($short_name, $full_name, @other_names)
1665 = prop_value_aliases("Gc", "Punct");
1666 my $same_full_name = prop_value_aliases("Gc", "P"); # Scalar cntxt
1667 my ($same_short_name) = prop_value_aliases("Gc", "P"); # gets 0th
1669 print "The full name is $full_name\n";
1670 print "The short name is $short_name\n";
1671 print "The other aliases are: ", join(", ", @other_names), "\n";
1674 The full name is Punctuation
1676 The other aliases are: Punct
1678 Some Unicode properties have a restricted set of legal values. For example,
1679 all binary properties are restricted to just C<true> or C<false>; and there
1680 are only a few dozen possible General Categories.
1682 For such properties, there are usually several synonyms for each possible
1683 value. For example, in binary properties, I<truth> can be represented by any of
1684 the strings "Y", "Yes", "T", or "True"; and the General Category
1685 "Punctuation" by that string, or "Punct", or simply "P".
1687 Like property names, there is typically at least a short name for each such
1688 property-value, and a long name. If you know any name of the property-value,
1689 you can use C<prop_value_aliases>() to get the long name (when called in
1690 scalar context), or a list of all the names, with the short name in the 0th
1691 element, the long name in the next element, and any other synonyms in the
1692 remaining elements, in no particular order, except that any all-numeric
1693 synonyms will be last.
1695 The long name is returned in a form nicely capitalized, suitable for printing.
1697 Case, white space, hyphens, and underscores are ignored in the input parameters
1698 (except for the trailing underscore in the old-form grandfathered-in general
1699 category property value C<"L_">, which is better written as C<"LC">).
1701 If either name is unknown, C<undef> is returned. Note that Perl typically
1702 recognizes property names in regular expressions with an optional C<"Is_>"
1703 (with or without the underscore) prefixed to them, such as C<\p{isgc=punct}>.
1704 This function does not recognize those in the property parameter, returning
1707 If called with a property that doesn't have synonyms for its values, it
1708 returns the input value, possibly normalized with capitalization and
1711 For the block property, new-style block names are returned (see
1712 L</Old-style versus new-style block names>).
1714 To find the synonyms for single-forms, such as C<\p{Any}>, use
1715 L</prop_aliases()> instead.
1717 C<prop_value_aliases> does not know about any user-defined properties, and
1718 will return C<undef> if called with one of those.
1722 # These are created by mktables for this routine and stored in unicore/UCD.pl
1723 # where their structures are described.
1724 our %loose_to_standard_value;
1725 our %prop_value_aliases;
1727 sub prop_value_aliases ($$) {
1728 my ($prop, $value) = @_;
1729 return unless defined $prop && defined $value;
1731 require "unicore/UCD.pl";
1732 require "utf8_heavy.pl";
1734 # Find the property name synonym that's used as the key in other hashes,
1735 # which is element 0 in the returned list.
1736 ($prop) = prop_aliases($prop);
1738 $prop = utf8::_loose_name(lc $prop);
1740 # Here is a legal property, but the hash below (created by mktables for
1741 # this purpose) only knows about the properties that have a very finite
1742 # number of potential values, that is not ones whose value could be
1743 # anything, like most (if not all) string properties. These don't have
1744 # synonyms anyway. Simply return the input. For example, there is no
1745 # synonym for ('Uppercase_Mapping', A').
1746 return $value if ! exists $prop_value_aliases{$prop};
1748 # The value name may be loosely or strictly matched; we don't know yet.
1749 # But both types use lower-case.
1752 # If the name isn't found under loose matching, it certainly won't be
1753 # found under strict
1754 my $loose_value = utf8::_loose_name($value);
1755 return unless exists $loose_to_standard_value{"$prop=$loose_value"};
1757 # Similarly if the combination under loose matching doesn't exist, it
1758 # won't exist under strict.
1759 my $standard_value = $loose_to_standard_value{"$prop=$loose_value"};
1760 return unless exists $prop_value_aliases{$prop}{$standard_value};
1762 # Here we did find a combination under loose matching rules. But it could
1763 # be that is a strict property match that shouldn't have matched.
1764 # %prop_value_aliases is set up so that the strict matches will appear as
1765 # if they were in loose form. Thus, if the non-loose version is legal,
1766 # we're ok, can skip the further check.
1767 if (! exists $utf8::stricter_to_file_of{"$prop=$value"}
1769 # We're also ok and skip the further check if value loosely matches.
1770 # mktables has verified that no strict name under loose rules maps to
1771 # an existing loose name. This code relies on the very limited
1772 # circumstances that strict names can be here. Strict name matching
1773 # happens under two conditions:
1774 # 1) when the name begins with an underscore. But this function
1775 # doesn't accept those, and %prop_value_aliases doesn't have
1777 # 2) When the values are numeric, in which case we need to look
1778 # further, but their squeezed-out loose values will be in
1779 # %stricter_to_file_of
1780 && exists $utf8::stricter_to_file_of{"$prop=$loose_value"})
1782 # The only thing that's legal loosely under strict is that can have an
1783 # underscore between digit pairs XXX
1784 while ($value =~ s/(\d)_(\d)/$1$2/g) {}
1785 return unless exists $utf8::stricter_to_file_of{"$prop=$value"};
1788 # Here, we know that the combination exists. Return it.
1789 my $list_ref = $prop_value_aliases{$prop}{$standard_value};
1790 if (@$list_ref > 1) {
1791 # The full name is in element 1.
1792 return $list_ref->[1] unless wantarray;
1794 return @{dclone $list_ref};
1797 return $list_ref->[0] unless wantarray;
1799 # Only 1 element means that it repeats
1800 return ( $list_ref->[0], $list_ref->[0] );
1803 # All 1 bits is the largest possible UV.
1804 $Unicode::UCD::MAX_CP = ~0;
1808 =head2 B<prop_invlist()>
1810 C<prop_invlist> returns an inversion list (described below) that defines all the
1811 code points for the binary Unicode property (or "property=value" pair) given
1812 by the input parameter string:
1815 use Unicode::UCD 'prop_invlist';
1816 say join ", ", prop_invlist("Any");
1821 An empty list is returned if the input is unknown; the number of elements in
1822 the list is returned if called in scalar context.
1824 L<perluniprops|perluniprops/Properties accessible through \p{} and \P{}> gives
1825 the list of properties that this function accepts, as well as all the possible
1826 forms for them (including with the optional "Is_" prefixes). (Except this
1827 function doesn't accept any Perl-internal properties, some of which are listed
1828 there.) This function uses the same loose or tighter matching rules for
1829 resolving the input property's name as is done for regular expressions. These
1830 are also specified in L<perluniprops|perluniprops/Properties accessible
1831 through \p{} and \P{}>. Examples of using the "property=value" form are:
1833 say join ", ", prop_invlist("Script=Shavian");
1838 say join ", ", prop_invlist("ASCII_Hex_Digit=No");
1841 0, 48, 58, 65, 71, 97, 103
1843 say join ", ", prop_invlist("ASCII_Hex_Digit=Yes");
1846 48, 58, 65, 71, 97, 103
1848 Inversion lists are a compact way of specifying Unicode property-value
1849 definitions. The 0th item in the list is the lowest code point that has the
1850 property-value. The next item (item [1]) is the lowest code point beyond that
1851 one that does NOT have the property-value. And the next item beyond that
1852 ([2]) is the lowest code point beyond that one that does have the
1853 property-value, and so on. Put another way, each element in the list gives
1854 the beginning of a range that has the property-value (for even numbered
1855 elements), or doesn't have the property-value (for odd numbered elements).
1856 The name for this data structure stems from the fact that each element in the
1857 list toggles (or inverts) whether the corresponding range is or isn't on the
1860 In the final example above, the first ASCII Hex digit is code point 48, the
1861 character "0", and all code points from it through 57 (a "9") are ASCII hex
1862 digits. Code points 58 through 64 aren't, but 65 (an "A") through 70 (an "F")
1863 are, as are 97 ("a") through 102 ("f"). 103 starts a range of code points
1864 that aren't ASCII hex digits. That range extends to infinity, which on your
1865 computer can be found in the variable C<$Unicode::UCD::MAX_CP>. (This
1866 variable is as close to infinity as Perl can get on your platform, and may be
1867 too high for some operations to work; you may wish to use a smaller number for
1870 Note that the inversion lists returned by this function can possibly include
1871 non-Unicode code points, that is anything above 0x10FFFF. This is in
1872 contrast to Perl regular expression matches on those code points, in which a
1873 non-Unicode code point always fails to match. For example, both of these have
1876 chr(0x110000) =~ \p{ASCII_Hex_Digit=True} # Fails.
1877 chr(0x110000) =~ \p{ASCII_Hex_Digit=False} # Fails!
1879 And both raise a warning that a Unicode property is being used on a
1880 non-Unicode code point. It is arguable as to which is the correct thing to do
1881 here. This function has chosen the way opposite to the Perl regular
1882 expression behavior. This allows you to easily flip to to the Perl regular
1883 expression way (for you to go in the other direction would be far harder).
1884 Simply add 0x110000 at the end of the non-empty returned list if it isn't
1885 already that value; and pop that value if it is; like:
1887 my @list = prop_invlist("foo");
1889 if ($list[-1] == 0x110000) {
1890 pop @list; # Defeat the turning on for above Unicode
1893 push @list, 0x110000; # Turn off for above Unicode
1897 It is a simple matter to expand out an inversion list to a full list of all
1898 code points that have the property-value:
1900 my @invlist = prop_invlist($property_name);
1901 die "empty" unless @invlist;
1903 for (my $i = 0; $i < @invlist; $i += 2) {
1904 my $upper = ($i + 1) < @invlist
1905 ? $invlist[$i+1] - 1 # In range
1906 : $Unicode::UCD::MAX_CP; # To infinity. You may want
1907 # to stop much much earlier;
1908 # going this high may expose
1909 # perl deficiencies with very
1911 for my $j ($invlist[$i] .. $upper) {
1912 push @full_list, $j;
1916 C<prop_invlist> does not know about any user-defined nor Perl internal-only
1917 properties, and will return C<undef> if called with one of those.
1921 # User-defined properties could be handled with some changes to utf8_heavy.pl;
1922 # and implementing here of dealing with EXTRAS. If done, consideration should
1923 # be given to the fact that the user subroutine could return different results
1924 # with each call; security issues need to be thought about.
1926 # These are created by mktables for this routine and stored in unicore/UCD.pl
1927 # where their structures are described.
1928 our %loose_defaults;
1929 our $MAX_UNICODE_CODEPOINT;
1931 sub prop_invlist ($) {
1933 return if ! defined $prop;
1935 require "utf8_heavy.pl";
1937 # Warnings for these are only for regexes, so not applicable to us
1938 no warnings 'deprecated';
1940 # Get the swash definition of the property-value.
1941 my $swash = utf8::SWASHNEW(__PACKAGE__, $prop, undef, 1, 0);
1943 # Fail if not found, or isn't a boolean property-value, or is a
1944 # user-defined property, or is internal-only.
1947 || $swash->{'BITS'} != 1
1948 || $swash->{'USER_DEFINED'}
1949 || $prop =~ /^\s*_/;
1951 if ($swash->{'EXTRAS'}) {
1952 carp __PACKAGE__, "::prop_invlist: swash returned for $prop unexpectedly has EXTRAS magic";
1955 if ($swash->{'SPECIALS'}) {
1956 carp __PACKAGE__, "::prop_invlist: swash returned for $prop unexpectedly has SPECIALS magic";
1962 # The input lines look like:
1966 # Split into lines, stripped of trailing comments
1967 foreach my $range (split "\n",
1968 $swash->{'LIST'} =~ s/ \s* (?: \# .* )? $ //xmgr)
1970 # And find the beginning and end of the range on the line
1971 my ($hex_begin, $hex_end) = split "\t", $range;
1972 my $begin = hex $hex_begin;
1974 # If the new range merely extends the old, we remove the marker
1975 # created the last time through the loop for the old's end, which
1976 # causes the new one's end to be used instead.
1977 if (@invlist && $begin == $invlist[-1]) {
1981 # Add the beginning of the range
1982 push @invlist, $begin;
1985 if (defined $hex_end) { # The next item starts with the code point 1
1986 # beyond the end of the range.
1987 push @invlist, hex($hex_end) + 1;
1989 else { # No end of range, is a single code point.
1990 push @invlist, $begin + 1;
1994 require "unicore/UCD.pl";
1995 my $FIRST_NON_UNICODE = $MAX_UNICODE_CODEPOINT + 1;
1997 # Could need to be inverted: add or subtract a 0 at the beginning of the
1998 # list. And to keep it from matching non-Unicode, add or subtract the
1999 # first non-unicode code point.
2000 if ($swash->{'INVERT_IT'}) {
2001 if (@invlist && $invlist[0] == 0) {
2005 unshift @invlist, 0;
2007 if (@invlist && $invlist[-1] == $FIRST_NON_UNICODE) {
2011 push @invlist, $FIRST_NON_UNICODE;
2015 # Here, the list is set up to include only Unicode code points. But, if
2016 # the table is the default one for the property, it should contain all
2017 # non-Unicode code points. First calculate the loose name for the
2018 # property. This is done even for strict-name properties, as the data
2019 # structure that mktables generates for us is set up so that we don't have
2020 # to worry about that. The property-value needs to be split if compound,
2021 # as the loose rules need to be independently calculated on each part. We
2022 # know that it is syntactically valid, or SWASHNEW would have failed.
2025 my ($prop_only, $table) = split /\s*[:=]\s*/, $prop;
2028 # May have optional prefixed 'is'
2029 $prop = utf8::_loose_name($prop_only) =~ s/^is//r;
2030 $prop = $utf8::loose_property_name_of{$prop};
2031 $prop .= "=" . utf8::_loose_name($table);
2034 $prop = utf8::_loose_name($prop);
2036 if (exists $loose_defaults{$prop}) {
2038 # Here, is the default table. If a range ended with 10ffff, instead
2039 # continue that range to infinity, by popping the 110000; otherwise,
2040 # add the range from 11000 to infinity
2041 if (! @invlist || $invlist[-1] != $FIRST_NON_UNICODE) {
2042 push @invlist, $FIRST_NON_UNICODE;
2052 sub _search_invlist {
2053 # Find the range in the inversion list which contains a code point; that
2054 # is, find i such that l[i] <= code_point < l[i+1]
2056 # If this is ever made public, could use to speed up .t specials. Would
2057 # need to use code point argument, as in other functions in this pm
2059 my $list_ref = shift;
2060 my $code_point = shift;
2061 # Verify non-neg numeric XXX
2063 my $max_element = @$list_ref - 1;
2064 return if ! $max_element < 0; # Undef if list is empty.
2066 # Short cut something at the far-end of the table. This also allows us to
2067 # refer to element [$i+1] without fear of being out-of-bounds in the loop
2069 return $max_element if $code_point >= $list_ref->[$max_element];
2071 use integer; # want integer division
2073 my $i = $max_element / 2;
2076 my $upper = $max_element;
2079 if ($code_point >= $list_ref->[$i]) {
2081 # Here we have met the lower constraint. We can quit if we
2082 # also meet the upper one.
2083 last if $code_point < $list_ref->[$i+1];
2085 $lower = $i; # Still too low.
2090 # Here, $code_point < $list_ref[$i], so look lower down.
2094 # Split search domain in half to try again.
2095 my $temp = ($upper + $lower) / 2;
2097 # No point in continuing unless $i changes for next time
2099 return $i if $temp == $i;
2101 } # End of while loop
2103 # Here we have found the offset
2109 =head2 B<prop_invmap()>
2111 use Unicode::UCD 'prop_invmap';
2112 my ($list_ref, $map_ref, $format, $missing)
2113 = prop_invmap("General Category");
2115 C<prop_invmap> is used to get the complete mapping definition for a property,
2116 in the form of an inversion map. An inversion map consists of two parallel
2117 arrays. One is an ordered list of code points that mark range beginnings, and
2118 the other gives the value (or mapping) that all code points in the
2119 corresponding range have.
2121 C<prop_invmap> is called with the name of the desired property. The name is
2122 loosely matched, meaning that differences in case, white-space, hyphens, and
2123 underscores are not meaningful (except for the trailing underscore in the
2124 old-form grandfathered-in property C<"L_">, which is better written as C<"LC">,
2125 or even better, C<"Gc=LC">).
2127 Many Unicode properties have more than one name (or alias). C<prop_invmap>
2128 understands all of these, including Perl extensions to them. Ambiguities are
2129 resolved as described above for L</prop_aliases()>. The Perl internal
2130 property "Perl_Decimal_Digit, described below, is also accepted. C<undef> is
2131 returned if the property name is unknown.
2132 See L<perluniprops/Properties accessible through Unicode::UCD> for the
2133 properties acceptable as inputs to this function.
2135 It is a fatal error to call this function except in list context.
2137 In addition to the the two arrays that form the inversion map, C<prop_invmap>
2138 returns two other values; one is a scalar that gives some details as to the
2139 format of the entries of the map array; the other is used for specialized
2140 purposes, described at the end of this section.
2142 This means that C<prop_invmap> returns a 4 element list. For example,
2144 my ($blocks_ranges_ref, $blocks_maps_ref, $format, $default)
2145 = prop_invmap("Block");
2147 In this call, the two arrays will be populated as shown below (for Unicode
2150 Index @blocks_ranges @blocks_maps
2151 0 0x0000 Basic Latin
2152 1 0x0080 Latin-1 Supplement
2153 2 0x0100 Latin Extended-A
2154 3 0x0180 Latin Extended-B
2155 4 0x0250 IPA Extensions
2156 5 0x02B0 Spacing Modifier Letters
2157 6 0x0300 Combining Diacritical Marks
2158 7 0x0370 Greek and Coptic
2161 233 0x2B820 No_Block
2162 234 0x2F800 CJK Compatibility Ideographs Supplement
2163 235 0x2FA20 No_Block
2165 237 0xE0080 No_Block
2166 238 0xE0100 Variation Selectors Supplement
2167 239 0xE01F0 No_Block
2168 240 0xF0000 Supplementary Private Use Area-A
2169 241 0x100000 Supplementary Private Use Area-B
2170 242 0x110000 No_Block
2172 The first line (with Index [0]) means that the value for code point 0 is "Basic
2173 Latin". The entry "0x0080" in the @blocks_ranges column in the second line
2174 means that the value from the first line, "Basic Latin", extends to all code
2175 points in the range from 0 up to but not including 0x0080, that is, through
2176 255. In other words, the code points from 0 to 255 are all in the "Basic
2177 Latin" block. Similarly, all code points in the range from 0x0080 up to (but
2178 not including) 0x0100 are in the block named "Latin-1 Supplement", etc.
2179 (Notice that the return is the old-style block names; see L</Old-style versus
2180 new-style block names>).
2182 The final line (with Index [242]) means that the value for all code points above
2183 the legal Unicode maximum code point have the value "No_Block", which is the
2184 term Unicode uses for a non-existing block.
2186 The arrays completely specify the mappings for all possible code points.
2187 The final element in an inversion map returned by this function will always be
2188 for the range that consists of all the code points that aren't legal Unicode,
2189 but that are expressible on the platform. (That is, it starts with code point
2190 0x110000, the first code point above the legal Unicode maximum, and extends to
2191 infinity.) The value for that range will be the same that any typical
2192 unassigned code point has for the specified property. (Certain unassigned
2193 code points are not "typical"; for example the non-character code points, or
2194 those in blocks that are to be written right-to-left. The above-Unicode
2195 range's value is not based on these atypical code points.) It could be argued
2196 that, instead of treating these as unassigned Unicode code points, the value
2197 for this range should be C<undef>. If you wish, you can change the returned
2200 The maps are almost always simple scalars that should be interpreted as-is.
2201 These values are those given in the Unicode-supplied data files, which may be
2202 inconsistent as to capitalization and as to which synonym for a property-value
2203 is given. The results may be normalized by using the L</prop_value_aliases()>
2206 There are exceptions to the simple scalar maps. Some properties have some
2207 elements in their map list that are themselves lists of scalars; and some
2208 special strings are returned that are not to be interpreted as-is. Element
2209 [2] (placed into C<$format> in the example above) of the returned four element
2210 list tells you if the map has any of these special elements, as follows:
2216 means all the elements of the map array are simple scalars, with no special
2217 elements. Almost all properties are like this, like the C<block> example
2222 means that some of the map array elements have the form given by C<s>, and
2223 the rest are lists of scalars. For example, here is a portion of the output
2224 of calling C<prop_invmap>() with the "Script Extensions" property:
2226 @scripts_ranges @scripts_maps
2229 0x0964 [ Bengali, Devanagari, Gurumukhi, Oriya ]
2233 Here, the code points 0x964 and 0x965 are used in the Bengali,
2234 Devanagari, Gurmukhi, and Oriya scripts.
2236 The Name_Alias property is of this form. But each scalar consists of two
2237 components: 1) the name, and 2) the type of alias this is. They are
2238 separated by a colon and a space. In Unicode 6.1, there are several alias types:
2244 indicates that the name is a corrected form for the
2245 original name (which remains valid) for the same code point.
2249 adds a new name for a control character.
2253 is an alternate name for a character
2257 is a name for a character that has been documented but was never in any
2260 =item C<abbreviation>
2262 is a common abbreviation for a character
2266 The lists are ordered (roughly) so the most preferred names come before less
2271 @aliases_ranges @alias_maps
2273 0x009E [ 'PRIVACY MESSAGE: control', 'PM: abbreviation' ]
2274 0x009F [ 'APPLICATION PROGRAM COMMAND: control',
2277 0x00A0 'NBSP: abbreviation'
2279 0x00AD 'SHY: abbreviation'
2281 0x01A2 'LATIN CAPITAL LETTER GHA: correction'
2282 0x01A3 'LATIN SMALL LETTER GHA: correction'
2286 A map to the empty string means that there is no alias defined for the code
2291 means that all the elements of the map array are either rational numbers or
2292 the string C<"NaN">, meaning "Not a Number". A rational number is either an
2293 integer, or two integers separated by a solidus (C<"/">). The second integer
2294 represents the denominator of the division implied by the solidus, and is
2295 guaranteed not to be 0. If you want to convert them to scalar numbers, you
2296 can use something like this:
2298 my ($invlist_ref, $invmap_ref, $format) = prop_invmap($property);
2299 if ($format && $format eq "r") {
2300 map { $_ = eval $_ } @$invmap_ref;
2303 Here's some entries from the output of the property "Nv", which has format
2306 @numerics_ranges @numerics_maps Note
2316 0xB2 2 SUPERSCRIPT 2
2317 0xB3 3 SUPERSCRIPT 2
2319 0xB9 1 SUPERSCRIPT 1
2321 0xBC 1/4 VULGAR FRACTION 1/4
2322 0xBD 1/2 VULGAR FRACTION 1/2
2323 0xBE 3/4 VULGAR FRACTION 3/4
2325 0x660 0 ARABIC-INDIC DIGIT ZERO
2329 is like C<s> in that all the map array elements are scalars, but some of them
2330 are the special string S<C<"E<lt>code pointE<gt>">>, meaning that the map of
2331 each code point in the corresponding range in the inversion list is the code
2332 point itself. For example, in:
2334 my ($uppers_ranges_ref, $uppers_maps_ref, $format)
2335 = prop_invmap("Simple_Uppercase_Mapping");
2337 the returned arrays look like this:
2339 @$uppers_ranges_ref @$uppers_maps_ref Note
2341 97 65 'a' maps to 'A'
2349 181 924 MICRO SIGN => Greek Cap MU
2353 The first line means that the uppercase of code point 0 is 0;
2354 the uppercase of code point 1 is 1; ... of code point 96 is 96. Without the
2355 C<"E<lt>code_pointE<gt>"> notation, every code point would have to have an
2356 entry. This would mean that the arrays would each have more than a million
2357 entries to list just the legal Unicode code points!
2361 means that some of the map array elements have the form given by C<c>, and
2362 the rest are ordered lists of code points.
2365 my ($uppers_ranges_ref, $uppers_maps_ref, $format)
2366 = prop_invmap("Uppercase_Mapping");
2368 the returned arrays look like this:
2370 @$uppers_ranges_ref @$uppers_maps_ref
2379 0x0149 [ 0x02BC 0x004E ]
2380 0x014A "<code point>"
2384 This is the full Uppercase_Mapping property (as opposed to the
2385 Simple_Uppercase_Mapping given in the example for format C<"c">). The only
2386 difference between the two in the ranges shown is that the code point at
2387 0x0149 (LATIN SMALL LETTER N PRECEDED BY APOSTROPHE) maps to a string of two
2388 characters, 0x02BC (MODIFIER LETTER APOSTROPHE) followed by 0x004E (LATIN
2393 means that some of the map array elements have the forms given by C<cl>, and
2394 the rest are the empty string. The property C<NFKC_Casefold> has this form.
2395 An example slice is:
2397 @$ranges_ref @$maps_ref Note
2399 0x00AA 0x0061 FEMININE ORDINAL INDICATOR => 'a'
2401 0x00AD SOFT HYPHEN => ""
2403 0x00AF [ 0x0020, 0x0304 ] MACRON => SPACE . COMBINING MACRON
2409 means the Name property. All the elements of the map array are simple
2410 scalars, but some of them contain special strings that require more work to
2411 get the actual name.
2415 CJK UNIFIED IDEOGRAPH-<code point>
2417 mean that the name for the code point is "CJK UNIFIED IDEOGRAPH-"
2418 with the code point (expressed in hexadecimal) appended to it, like "CJK
2419 UNIFIED IDEOGRAPH-3403" (similarly for C<CJK COMPATIBILITY IDEOGRAPH-E<lt>code
2426 means that the name is algorithmically calculated. This is easily done by
2427 the function L<charnames/charnames::viacode(code)>.
2429 Note that for control characters (C<Gc=cc>), Unicode's data files have the
2430 string "C<E<lt>controlE<gt>>", but the real name of each of these characters is the empty
2431 string. This function returns that real name, the empty string. (There are
2432 names for these characters, but they are aliases, not the real name, and are
2433 contained in the C<Name_Alias> property.)
2437 means the Decomposition_Mapping property. This property is like C<cl>
2438 properties, except it has an additional entry type:
2442 for those code points whose decomposition is algorithmically calculated. (The
2443 C<n> format has this same entry.) These can be generated via the function
2444 L<Unicode::Normalize::NFD()|Unicode::Normalize>.
2447 Note that the mapping is the one that is specified in the Unicode data files,
2448 and to get the final decomposition, it may need to be applied recursively.
2452 A binary search can be used to quickly find a code point in the inversion
2453 list, and hence its corresponding mapping.
2455 The final element (index [3], assigned to C<$default> in the "block" example) in
2456 the four element list returned by this function may be useful for applications
2457 that wish to convert the returned inversion map data structure into some
2458 other, such as a hash. It gives the mapping that most code points map to
2459 under the property. If you establish the convention that any code point not
2460 explicitly listed in your data structure maps to this value, you can
2461 potentially make your data structure much smaller. As you construct your data
2462 structure from the one returned by this function, simply ignore those ranges
2463 that map to this value, generally called the "default" value. For example, to
2464 convert to the data structure searchable by L</charinrange()>, you can follow
2467 my ($list_ref, $map_ref, $format, $missing) = prop_invmap($property);
2469 for my $i (0 .. @$list_ref - 2) {
2470 next if $map_ref->[$i] eq $missing;
2471 push @range_list, [ $list_ref->[$i],
2477 print charinrange(\@range_list, $code_point), "\n";
2480 With this, C<charinrange()> will return C<undef> if its input code point maps
2481 to C<$missing>. You can avoid this by omitting the C<next> statement, and adding
2482 a line after the loop to handle the final element of the inversion map.
2484 One internal Perl property is accessible by this function.
2485 "Perl_Decimal_Digit" returns an inversion map in which all the Unicode decimal
2486 digits map to their numeric values, and everything else to the empty string,
2506 Note that the inversion maps returned for the C<Case_Folding> and
2507 C<Simple_Case_Folding> properties do not include the Turkic-locale mappings.
2508 Use L</casefold()> for these.
2510 C<prop_invmap> does not know about any user-defined properties, and will
2511 return C<undef> if called with one of those.
2515 # User-defined properties could be handled with some changes to utf8_heavy.pl;
2516 # if done, consideration should be given to the fact that the user subroutine
2517 # could return different results with each call, which could lead to some
2520 # One could store things in memory so they don't have to be recalculated, but
2521 # it is unlikely this will be called often, and some properties would take up
2522 # significant memory.
2524 # These are created by mktables for this routine and stored in unicore/UCD.pl
2525 # where their structures are described.
2526 our @algorithmic_named_code_points;
2530 sub prop_invmap ($) {
2532 croak __PACKAGE__, "::prop_invmap: must be called in list context" unless wantarray;
2535 return unless defined $prop;
2537 # Fail internal properties
2538 return if $prop =~ /^_/;
2540 # The values returned by this function.
2541 my (@invlist, @invmap, $format, $missing);
2543 # The swash has two components we look at, the base list, and a hash,
2544 # named 'SPECIALS', containing any additional members whose mappings don't
2545 # fit into the the base list scheme of things. These generally 'override'
2546 # any value in the base list for the same code point.
2549 require "utf8_heavy.pl";
2550 require "unicore/UCD.pl";
2554 # Try to get the map swash for the property. They have 'To' prepended to
2555 # the property name, and 32 means we will accept 32 bit return values.
2556 my $swash = utf8::SWASHNEW(__PACKAGE__, "To$prop", undef, 32, 0);
2558 # If there are multiple entries for a single code point;
2559 my $has_multiples = 0;
2561 # If didn't find it, could be because needs a proxy. And if was the
2562 # 'Block' or 'Name' property, use a proxy even if did find it. Finding it
2563 # would be the result of the installation changing mktables to output the
2564 # Block or Name tables. The Block table gives block names in the
2565 # new-style, and this routine is supposed to return old-style block names.
2566 # The Name table is valid, but we need to execute the special code below
2567 # to add in the algorithmic-defined name entries.
2568 if (ref $swash eq ""
2569 || $swash->{'TYPE'} eq 'ToBlk'
2570 || $swash->{'TYPE'} eq 'ToNa')
2573 # Get the short name of the input property, in standard form
2574 my ($second_try) = prop_aliases($prop);
2575 return unless $second_try;
2576 $second_try = utf8::_loose_name(lc $second_try);
2578 if ($second_try eq "in") {
2580 # This property is identical to age for inversion map purposes
2584 elsif ($second_try =~ / ^ s ( cf | [ltu] c ) $ /x) {
2586 # These properties use just the LIST part of the full mapping,
2587 # which includes the simple maps that are otherwise overridden by
2588 # the SPECIALS. So all we need do is to not look at the SPECIALS;
2589 # set $overrides to indicate that
2592 # The full name is the simple name stripped of its initial 's'
2593 $prop = $second_try =~ s/^s//r;
2596 elsif ($second_try eq "blk") {
2598 # We use the old block names. Just create a fake swash from its
2602 $blocks{'LIST'} = "";
2603 $blocks{'TYPE'} = "ToBlk";
2604 $utf8::SwashInfo{ToBlk}{'missing'} = "No_Block";
2605 $utf8::SwashInfo{ToBlk}{'format'} = "s";
2607 foreach my $block (@BLOCKS) {
2608 $blocks{'LIST'} .= sprintf "%x\t%x\t%s\n",
2615 elsif ($second_try eq "na") {
2617 # Use the combo file that has all the Name-type properties in it,
2618 # extracting just the ones that are for the actual 'Name'
2619 # property. And create a fake swash from it.
2621 $names{'LIST'} = "";
2622 my $original = do "unicore/Name.pl";
2623 my $algorithm_names = \@algorithmic_named_code_points;
2625 # We need to remove the names from it that are aliases. For that
2626 # we need to also read in that table. Create a hash with the keys
2627 # being the code points, and the values being a list of the
2628 # aliases for the code point key.
2629 my ($aliases_code_points, $aliases_maps, undef, undef) =
2630 &prop_invmap('Name_Alias');
2632 for (my $i = 0; $i < @$aliases_code_points; $i++) {
2633 my $code_point = $aliases_code_points->[$i];
2634 $aliases{$code_point} = $aliases_maps->[$i];
2636 # If not already a list, make it into one, so that later we
2637 # can treat things uniformly
2638 if (! ref $aliases{$code_point}) {
2639 $aliases{$code_point} = [ $aliases{$code_point} ];
2642 # Remove the alias type from the entry, retaining just the
2644 map { s/:.*// } @{$aliases{$code_point}};
2647 # We hold off on adding the next entry to the list until we know,
2648 # that the next line isn't for the same code point. We only
2649 # output the final line. That one is the original Name property
2650 # value. The others are the Name_Alias corrections, which are
2651 # listed first in the file.
2653 foreach my $line (split "\n", $original) {
2654 my ($hex_code_point, $name) = split "\t", $line;
2656 # Weeds out all comments, blank lines, and named sequences
2657 next if $hex_code_point =~ /\P{ASCII_HEX_DIGIT}/;
2659 my $code_point = hex $hex_code_point;
2661 # The name of all controls is the default: the empty string.
2662 # The set of controls is immutable, so these hard-coded
2664 next if $code_point <= 0x9F
2665 && ($code_point <= 0x1F || $code_point >= 0x7F);
2667 # If this is a name_alias, it isn't a name
2668 next if grep { $_ eq $name } @{$aliases{$code_point}};
2670 # If we are beyond where one of the special lines needs to
2672 while ($i < @$algorithm_names
2673 && $code_point > $algorithm_names->[$i]->{'low'})
2676 # ... then insert it, ahead of what we were about to
2678 $names{'LIST'} .= sprintf "%x\t%x\t%s\n",
2679 $algorithm_names->[$i]->{'low'},
2680 $algorithm_names->[$i]->{'high'},
2681 $algorithm_names->[$i]->{'name'};
2683 # Done with this range.
2686 # We loop until all special lines that precede the next
2687 # regular one are output.
2690 # Here, is a normal name.
2691 $names{'LIST'} .= sprintf "%x\t\t%s\n", $code_point, $name;
2692 } # End of loop through all the names
2694 $names{'TYPE'} = "ToNa";
2695 $utf8::SwashInfo{ToNa}{'missing'} = "";
2696 $utf8::SwashInfo{ToNa}{'format'} = "n";
2699 elsif ($second_try =~ / ^ ( d [mt] ) $ /x) {
2701 # The file is a combination of dt and dm properties. Create a
2702 # fake swash from the portion that we want.
2703 my $original = do "unicore/Decomposition.pl";
2706 if ($second_try eq 'dt') {
2707 $decomps{'TYPE'} = "ToDt";
2708 $utf8::SwashInfo{'ToDt'}{'missing'} = "None";
2709 $utf8::SwashInfo{'ToDt'}{'format'} = "s";
2712 $decomps{'TYPE'} = "ToDm";
2713 $utf8::SwashInfo{'ToDm'}{'missing'} = "<code point>";
2715 # Use a special internal-to-this_routine format, 'dm', to
2716 # distinguish from 'd', meaning decimal.
2717 $utf8::SwashInfo{'ToDm'}{'format'} = "dm";
2720 $decomps{'LIST'} = "";
2722 # This property has one special range not in the file: for the
2724 my $done_hangul = 0; # Have we done the hangul range.
2725 foreach my $line (split "\n", $original) {
2726 my ($hex_lower, $hex_upper, $type_and_map) = split "\t", $line;
2727 my $code_point = hex $hex_lower;
2730 # The type, enclosed in <...>, precedes the mapping separated
2732 if ($type_and_map =~ / ^ < ( .* ) > \s+ (.*) $ /x) {
2733 $value = ($second_try eq 'dt') ? $1 : $2
2735 else { # If there is no type specified, it's canonical
2736 $value = ($second_try eq 'dt')
2741 # Insert the hangul range at the appropriate spot.
2742 if (! $done_hangul && $code_point > $HANGUL_BEGIN) {
2745 sprintf "%x\t%x\t%s\n",
2747 $HANGUL_BEGIN + $HANGUL_COUNT - 1,
2748 ($second_try eq 'dt')
2750 : "<hangul syllable>";
2753 # And append this to our constructed LIST.
2754 $decomps{'LIST'} .= "$hex_lower\t$hex_upper\t$value\n";
2758 else { # Don't know this property. Fail.
2763 if ($swash->{'EXTRAS'}) {
2764 carp __PACKAGE__, "::prop_invmap: swash returned for $prop unexpectedly has EXTRAS magic";
2768 # Here, have a valid swash return. Examine it.
2769 my $returned_prop = $swash->{TYPE};
2771 # All properties but binary ones should have 'missing' and 'format'
2773 $missing = $utf8::SwashInfo{$returned_prop}{'missing'};
2774 $missing = 'N' unless defined $missing;
2776 $format = $utf8::SwashInfo{$returned_prop}{'format'};
2777 $format = 'b' unless defined $format;
2779 # The LIST input lines look like:
2782 # 0375\t0377\tGreek # [3]
2783 # 037A\t037D\tGreek # [4]
2788 # Convert them to like
2797 # For binary properties, the final non-comment column is absent, and
2798 # assumed to be 'Y'.
2800 foreach my $range (split "\n", $swash->{'LIST'}) {
2801 $range =~ s/ \s* (?: \# .* )? $ //xg; # rmv trailing space, comments
2803 # Find the beginning and end of the range on the line
2804 my ($hex_begin, $hex_end, $map) = split "\t", $range;
2805 my $begin = hex $hex_begin;
2806 my $end = (defined $hex_end && $hex_end ne "")
2810 # Each time through the loop (after the first):
2811 # $invlist[-2] contains the beginning of the previous range processed
2812 # $invlist[-1] contains the end+1 of the previous range processed
2813 # $invmap[-2] contains the value of the previous range processed
2814 # $invmap[-1] contains the default value for missing ranges ($missing)
2816 # Thus, things are set up for the typical case of a new non-adjacent
2817 # range of non-missings to be added. But, if the new range is
2818 # adjacent, it needs to replace the [-1] elements; and if the new
2819 # range is a multiple value of the previous one, it needs to be added
2820 # to the [-2] map element.
2822 # The first time through, everything will be empty. If the property
2823 # doesn't have a range that begins at 0, add one that maps to $missing
2827 push @invmap, $missing;
2830 elsif (@invlist > 1 && $invlist[-2] == $begin) {
2832 # Here we handle the case where the input has multiple entries for
2833 # each code point. mktables should have made sure that each such
2834 # range contains only one code point. At this point, $invlist[-1]
2835 # is the $missing that was added at the end of the last loop
2836 # iteration, and [-2] is the last real input code point, and that
2837 # code point is the same as the one we are adding now, making the
2838 # new one a multiple entry. Add it to the existing entry, either
2839 # by pushing it to the existing list of multiple entries, or
2840 # converting the single current entry into a list with both on it.
2841 # This is all we need do for this iteration.
2843 if ($end != $begin) {
2844 croak __PACKAGE__, "Multiple maps per code point in '$prop' require single-element ranges: begin=$begin, end=$end, map=$map";
2846 if (! ref $invmap[-2]) {
2847 $invmap[-2] = [ $invmap[-2], $map ];
2850 push @{$invmap[-2]}, $map;
2855 elsif ($invlist[-1] == $begin) {
2857 # If the input isn't in the most compact form, so that there are
2858 # two adjacent ranges that map to the same thing, they should be
2859 # combined. This happens in our constructed dt mapping, as
2860 # Element [-2] is the map for the latest range so far processed.
2861 # Just set the beginning point of the map to $missing (in
2862 # invlist[-1]) to 1 beyond where this range ends. For example, in
2865 # we have set it up so that it looks like
2869 # We now see that it should be
2872 if (@invlist > 1 && ( (defined $map)
2873 ? $invmap[-2] eq $map
2874 : $invmap[-2] eq 'Y'))
2876 $invlist[-1] = $end + 1;
2880 # Here, the range started in the previous iteration that maps to
2881 # $missing starts at the same code point as this range. That
2882 # means there is no gap to fill that that range was intended for,
2883 # so we just pop it off the parallel arrays.
2888 # Add the range beginning, and the range's map.
2889 push @invlist, $begin;
2890 if ($format eq 'dm') {
2892 # The decomposition maps are either a line like <hangul syllable>
2893 # which are to be taken as is; or a sequence of code points in hex
2894 # and separated by blanks. Convert them to decimal, and if there
2895 # is more than one, use an anonymous array as the map.
2896 if ($map =~ /^ < /x) {
2900 my @map = map { hex } split " ", $map;
2902 push @invmap, $map[0];
2905 push @invmap, \@map;
2911 # Otherwise, convert hex formatted list entries to decimal; add a
2912 # 'Y' map for the missing value in binary properties, or
2913 # otherwise, use the input map unchanged.
2914 $map = ($format eq 'x')
2922 # We just started a range. It ends with $end. The gap between it and
2923 # the next element in the list must be filled with a range that maps
2924 # to the default value. If there is no gap, the next iteration will
2925 # pop this, unless there is no next iteration, and we have filled all
2926 # of the Unicode code space, so check for that and skip.
2927 if ($end < $MAX_UNICODE_CODEPOINT) {
2928 push @invlist, $end + 1;
2929 push @invmap, $missing;
2933 # If the property is empty, make all code points use the value for missing
2937 push @invmap, $missing;
2940 # And add in standard element that all non-Unicode code points map to
2942 push @invlist, $MAX_UNICODE_CODEPOINT + 1;
2943 push @invmap, $missing;
2945 # The second component of the map are those values that require
2946 # non-standard specification, stored in SPECIALS. These override any
2947 # duplicate code points in LIST. If we are using a proxy, we may have
2948 # already set $overrides based on the proxy.
2949 $overrides = $swash->{'SPECIALS'} unless defined $overrides;
2952 # A negative $overrides implies that the SPECIALS should be ignored,
2953 # and a simple 'c' list is the value.
2954 if ($overrides < 0) {
2959 # Currently, all overrides are for properties that normally map to
2960 # single code points, but now some will map to lists of code
2961 # points (but there is an exception case handled below).
2964 # Look through the overrides.
2965 foreach my $cp_maybe_utf8 (keys %$overrides) {
2969 # If the overrides came from SPECIALS, the code point keys are
2971 if ($overrides == $swash->{'SPECIALS'}) {
2972 $cp = unpack("C0U", $cp_maybe_utf8);
2973 @map = unpack "U0U*", $swash->{'SPECIALS'}{$cp_maybe_utf8};
2975 # The empty string will show up unpacked as an empty
2977 $format = 'cle' if @map == 0;
2981 # But if we generated the overrides, we didn't bother to
2982 # pack them, and we, so far, do this only for properties
2983 # that are 'c' ones.
2984 $cp = $cp_maybe_utf8;
2985 @map = hex $overrides->{$cp};
2989 # Find the range that the override applies to.
2990 my $i = _search_invlist(\@invlist, $cp);
2991 if ($cp < $invlist[$i] || $cp >= $invlist[$i + 1]) {
2992 croak __PACKAGE__, "wrong_range, cp=$cp; i=$i, current=$invlist[$i]; next=$invlist[$i + 1]"
2995 # And what that range currently maps to
2996 my $cur_map = $invmap[$i];
2998 # If there is a gap between the next range and the code point
2999 # we are overriding, we have to add elements to both arrays to
3000 # fill that gap, using the map that applies to it, which is
3001 # $cur_map, since it is part of the current range.
3002 if ($invlist[$i + 1] > $cp + 1) {
3004 #say "Before splice:";
3005 #say 'i-2=[', $i-2, ']', sprintf("%04X maps to %s", $invlist[$i-2], $invmap[$i-2]) if $i >= 2;
3006 #say 'i-1=[', $i-1, ']', sprintf("%04X maps to %s", $invlist[$i-1], $invmap[$i-1]) if $i >= 1;
3007 #say 'i =[', $i, ']', sprintf("%04X maps to %s", $invlist[$i], $invmap[$i]);
3008 #say 'i+1=[', $i+1, ']', sprintf("%04X maps to %s", $invlist[$i+1], $invmap[$i+1]) if $i < @invlist + 1;
3009 #say 'i+2=[', $i+2, ']', sprintf("%04X maps to %s", $invlist[$i+2], $invmap[$i+2]) if $i < @invlist + 2;
3011 splice @invlist, $i + 1, 0, $cp + 1;
3012 splice @invmap, $i + 1, 0, $cur_map;
3014 #say "After splice:";
3015 #say 'i-2=[', $i-2, ']', sprintf("%04X maps to %s", $invlist[$i-2], $invmap[$i-2]) if $i >= 2;
3016 #say 'i-1=[', $i-1, ']', sprintf("%04X maps to %s", $invlist[$i-1], $invmap[$i-1]) if $i >= 1;
3017 #say 'i =[', $i, ']', sprintf("%04X maps to %s", $invlist[$i], $invmap[$i]);
3018 #say 'i+1=[', $i+1, ']', sprintf("%04X maps to %s", $invlist[$i+1], $invmap[$i+1]) if $i < @invlist + 1;
3019 #say 'i+2=[', $i+2, ']', sprintf("%04X maps to %s", $invlist[$i+2], $invmap[$i+2]) if $i < @invlist + 2;
3022 # If the remaining portion of the range is multiple code
3023 # points (ending with the one we are replacing, guaranteed by
3024 # the earlier splice). We must split it into two
3025 if ($invlist[$i] < $cp) {
3026 $i++; # Compensate for the new element
3029 #say "Before splice:";
3030 #say 'i-2=[', $i-2, ']', sprintf("%04X maps to %s", $invlist[$i-2], $invmap[$i-2]) if $i >= 2;
3031 #say 'i-1=[', $i-1, ']', sprintf("%04X maps to %s", $invlist[$i-1], $invmap[$i-1]) if $i >= 1;
3032 #say 'i =[', $i, ']', sprintf("%04X maps to %s", $invlist[$i], $invmap[$i]);
3033 #say 'i+1=[', $i+1, ']', sprintf("%04X maps to %s", $invlist[$i+1], $invmap[$i+1]) if $i < @invlist + 1;
3034 #say 'i+2=[', $i+2, ']', sprintf("%04X maps to %s", $invlist[$i+2], $invmap[$i+2]) if $i < @invlist + 2;
3036 splice @invlist, $i, 0, $cp;
3037 splice @invmap, $i, 0, 'dummy';
3039 #say "After splice:";
3040 #say 'i-2=[', $i-2, ']', sprintf("%04X maps to %s", $invlist[$i-2], $invmap[$i-2]) if $i >= 2;
3041 #say 'i-1=[', $i-1, ']', sprintf("%04X maps to %s", $invlist[$i-1], $invmap[$i-1]) if $i >= 1;
3042 #say 'i =[', $i, ']', sprintf("%04X maps to %s", $invlist[$i], $invmap[$i]);
3043 #say 'i+1=[', $i+1, ']', sprintf("%04X maps to %s", $invlist[$i+1], $invmap[$i+1]) if $i < @invlist + 1;
3044 #say 'i+2=[', $i+2, ']', sprintf("%04X maps to %s", $invlist[$i+2], $invmap[$i+2]) if $i < @invlist + 2;
3047 # Here, the range we are overriding contains a single code
3048 # point. The result could be the empty string, a single
3049 # value, or a list. If the last case, we use an anonymous
3051 $invmap[$i] = (scalar @map == 0)
3059 elsif ($format eq 'x') {
3061 # All hex-valued properties are really to code points
3064 elsif ($format eq 'dm') {
3067 elsif ($format eq 'sw') { # blank-separated elements to form a list.
3068 map { $_ = [ split " ", $_ ] if $_ =~ / / } @invmap;
3071 elsif ($returned_prop eq 'ToNameAlias') {
3073 # This property currently doesn't have any lists, but theoretically
3077 elsif ($format ne 'n' && $format ne 'r') {
3079 # All others are simple scalars
3082 if ($has_multiples && $format !~ /l/) {
3083 croak __PACKAGE__, "Wrong format '$format' for prop_invmap('$prop'); should indicate has lists";
3086 return (\@invlist, \@invmap, $format, $missing);
3089 =head2 Unicode::UCD::UnicodeVersion
3091 This returns the version of the Unicode Character Database, in other words, the
3092 version of the Unicode standard the database implements. The version is a
3093 string of numbers delimited by dots (C<'.'>).
3099 sub UnicodeVersion {
3100 unless (defined $UNICODEVERSION) {
3101 openunicode(\$VERSIONFH, "version");
3103 chomp($UNICODEVERSION = <$VERSIONFH>);
3105 croak __PACKAGE__, "::VERSION: strange version '$UNICODEVERSION'"
3106 unless $UNICODEVERSION =~ /^\d+(?:\.\d+)+$/;
3108 return $UNICODEVERSION;
3111 =head2 B<Blocks versus Scripts>
3113 The difference between a block and a script is that scripts are closer
3114 to the linguistic notion of a set of code points required to present
3115 languages, while block is more of an artifact of the Unicode code point
3116 numbering and separation into blocks of (mostly) 256 code points.
3118 For example the Latin B<script> is spread over several B<blocks>, such
3119 as C<Basic Latin>, C<Latin 1 Supplement>, C<Latin Extended-A>, and
3120 C<Latin Extended-B>. On the other hand, the Latin script does not
3121 contain all the characters of the C<Basic Latin> block (also known as
3122 ASCII): it includes only the letters, and not, for example, the digits
3125 For blocks see L<http://www.unicode.org/Public/UNIDATA/Blocks.txt>
3127 For scripts see UTR #24: L<http://www.unicode.org/unicode/reports/tr24/>
3129 =head2 B<Matching Scripts and Blocks>
3131 Scripts are matched with the regular-expression construct
3132 C<\p{...}> (e.g. C<\p{Tibetan}> matches characters of the Tibetan script),
3133 while C<\p{Blk=...}> is used for blocks (e.g. C<\p{Blk=Tibetan}> matches
3134 any of the 256 code points in the Tibetan block).
3136 =head2 Old-style versus new-style block names
3138 Unicode publishes the names of blocks in two different styles, though the two
3139 are equivalent under Unicode's loose matching rules.
3141 The original style uses blanks and hyphens in the block names (except for
3142 C<No_Block>), like so:
3144 Miscellaneous Mathematical Symbols-B
3146 The newer style replaces these with underscores, like this:
3148 Miscellaneous_Mathematical_Symbols_B
3150 This newer style is consistent with the values of other Unicode properties.
3151 To preserve backward compatibility, all the functions in Unicode::UCD that
3152 return block names (except one) return the old-style ones. That one function,
3153 L</prop_value_aliases()> can be used to convert from old-style to new-style:
3155 my $new_style = prop_values_aliases("block", $old_style);
3157 Perl also has single-form extensions that refer to blocks, C<In_Cyrillic>,
3158 meaning C<Block=Cyrillic>. These have always been written in the new style.
3160 To convert from new-style to old-style, follow this recipe:
3162 $old_style = charblock((prop_invlist("block=$new_style"))[0]);
3164 (which finds the range of code points in the block using C<prop_invlist>,
3165 gets the lower end of the range (0th element) and then looks up the old name
3166 for its block using C<charblock>).
3168 Note that starting in Unicode 6.1, many of the block names have shorter
3169 synonyms. These are always given in the new style.
3173 Does not yet support EBCDIC platforms.
3177 Jarkko Hietaniemi. Now maintained by perl5 porters.