This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
t/uni/case.pl: Allow to work on early Unicodes
[perl5.git] / lib / Unicode / UCD.pm
CommitLineData
55d7b906 1package Unicode::UCD;
561c79ed
JH
2
3use strict;
4use warnings;
36c2430c 5no warnings 'surrogate'; # surrogates can be inputs to this
98ef7649 6use charnames ();
561c79ed 7
e80c2d9d 8our $VERSION = '0.44';
561c79ed
JH
9
10require Exporter;
11
12our @ISA = qw(Exporter);
74f8133e 13
10a6ecd2
JH
14our @EXPORT_OK = qw(charinfo
15 charblock charscript
16 charblocks charscripts
b08cd201 17 charinrange
ea508aee 18 general_categories bidi_types
b08cd201 19 compexcl
a2bd7410 20 casefold casespec
7319f91d
KW
21 namedseq
22 num
7ef25837
KW
23 prop_aliases
24 prop_value_aliases
681d705c 25 prop_invlist
62b3b855 26 prop_invmap
681d705c 27 MAX_CP
7319f91d 28 );
561c79ed
JH
29
30use Carp;
31
32=head1 NAME
33
55d7b906 34Unicode::UCD - Unicode character database
561c79ed
JH
35
36=head1 SYNOPSIS
37
55d7b906 38 use Unicode::UCD 'charinfo';
b08cd201 39 my $charinfo = charinfo($codepoint);
561c79ed 40
956cae9a
KW
41 use Unicode::UCD 'casefold';
42 my $casefold = casefold(0xFB00);
43
5d8e6e41
KW
44 use Unicode::UCD 'casespec';
45 my $casespec = casespec(0xFB00);
46
55d7b906 47 use Unicode::UCD 'charblock';
e882dd67
JH
48 my $charblock = charblock($codepoint);
49
55d7b906 50 use Unicode::UCD 'charscript';
65044554 51 my $charscript = charscript($codepoint);
561c79ed 52
55d7b906 53 use Unicode::UCD 'charblocks';
e145285f
JH
54 my $charblocks = charblocks();
55
55d7b906 56 use Unicode::UCD 'charscripts';
ea508aee 57 my $charscripts = charscripts();
e145285f 58
55d7b906 59 use Unicode::UCD qw(charscript charinrange);
e145285f
JH
60 my $range = charscript($script);
61 print "looks like $script\n" if charinrange($range, $codepoint);
62
ea508aee
JH
63 use Unicode::UCD qw(general_categories bidi_types);
64 my $categories = general_categories();
65 my $types = bidi_types();
66
7ef25837
KW
67 use Unicode::UCD 'prop_aliases';
68 my @space_names = prop_aliases("space");
69
70 use Unicode::UCD 'prop_value_aliases';
71 my @gc_punct_names = prop_value_aliases("Gc", "Punct");
72
681d705c
KW
73 use Unicode::UCD 'prop_invlist';
74 my @puncts = prop_invlist("gc=punctuation");
75
62b3b855
KW
76 use Unicode::UCD 'prop_invmap';
77 my ($list_ref, $map_ref, $format, $missing)
78 = prop_invmap("General Category");
79
55d7b906 80 use Unicode::UCD 'compexcl';
e145285f
JH
81 my $compexcl = compexcl($codepoint);
82
a2bd7410
JH
83 use Unicode::UCD 'namedseq';
84 my $namedseq = namedseq($named_sequence_name);
85
55d7b906 86 my $unicode_version = Unicode::UCD::UnicodeVersion();
e145285f 87
7319f91d 88 my $convert_to_numeric =
62a8c8c2 89 Unicode::UCD::num("\N{RUMI DIGIT ONE}\N{RUMI DIGIT TWO}");
7319f91d 90
561c79ed
JH
91=head1 DESCRIPTION
92
a452d459
KW
93The Unicode::UCD module offers a series of functions that
94provide a simple interface to the Unicode
8b731da2 95Character Database.
561c79ed 96
a452d459
KW
97=head2 code point argument
98
99Some of the functions are called with a I<code point argument>, which is either
100a decimal or a hexadecimal scalar designating a Unicode code point, or C<U+>
101followed by hexadecimals designating a Unicode code point. In other words, if
102you want a code point to be interpreted as a hexadecimal number, you must
103prefix it with either C<0x> or C<U+>, because a string like e.g. C<123> will be
f200dd12
KW
104interpreted as a decimal code point. Note that the largest code point in
105Unicode is U+10FFFF.
c3e5bc54 106
561c79ed
JH
107=cut
108
10a6ecd2 109my $BLOCKSFH;
10a6ecd2 110my $VERSIONFH;
b08cd201
JH
111my $CASEFOLDFH;
112my $CASESPECFH;
a2bd7410 113my $NAMEDSEQFH;
e80c2d9d 114my $v_unicode_version; # v-string.
561c79ed
JH
115
116sub openunicode {
117 my ($rfh, @path) = @_;
118 my $f;
119 unless (defined $$rfh) {
120 for my $d (@INC) {
121 use File::Spec;
55d7b906 122 $f = File::Spec->catfile($d, "unicore", @path);
32c16050 123 last if open($$rfh, $f);
e882dd67 124 undef $f;
561c79ed 125 }
e882dd67
JH
126 croak __PACKAGE__, ": failed to find ",
127 File::Spec->catfile(@path), " in @INC"
128 unless defined $f;
561c79ed
JH
129 }
130 return $f;
131}
132
cb3150f5
KW
133sub _dclone ($) { # Use Storable::dclone if available; otherwise emulate it.
134
135 use if defined &DynaLoader::boot_DynaLoader, Storable => qw(dclone);
136
137 return dclone(shift) if defined &dclone;
138
139 my $arg = shift;
140 my $type = ref $arg;
141 return $arg unless $type; # No deep cloning needed for scalars
142
143 if ($type eq 'ARRAY') {
144 my @return;
145 foreach my $element (@$arg) {
146 push @return, &_dclone($element);
147 }
148 return \@return;
149 }
150 elsif ($type eq 'HASH') {
151 my %return;
152 foreach my $key (keys %$arg) {
153 $return{$key} = &_dclone($arg->{$key});
154 }
155 return \%return;
156 }
157 else {
158 croak "_dclone can't handle " . $type;
159 }
160}
161
a452d459 162=head2 B<charinfo()>
561c79ed 163
55d7b906 164 use Unicode::UCD 'charinfo';
561c79ed 165
b08cd201 166 my $charinfo = charinfo(0x41);
561c79ed 167
a452d459
KW
168This returns information about the input L</code point argument>
169as a reference to a hash of fields as defined by the Unicode
170standard. If the L</code point argument> is not assigned in the standard
171(i.e., has the general category C<Cn> meaning C<Unassigned>)
172or is a non-character (meaning it is guaranteed to never be assigned in
173the standard),
a18e976f 174C<undef> is returned.
a452d459
KW
175
176Fields that aren't applicable to the particular code point argument exist in the
177returned hash, and are empty.
178
179The keys in the hash with the meanings of their values are:
180
181=over
182
183=item B<code>
184
185the input L</code point argument> expressed in hexadecimal, with leading zeros
186added if necessary to make it contain at least four hexdigits
187
188=item B<name>
189
190name of I<code>, all IN UPPER CASE.
191Some control-type code points do not have names.
192This field will be empty for C<Surrogate> and C<Private Use> code points,
193and for the others without a name,
194it will contain a description enclosed in angle brackets, like
195C<E<lt>controlE<gt>>.
196
197
198=item B<category>
199
200The short name of the general category of I<code>.
201This will match one of the keys in the hash returned by L</general_categories()>.
202
7ef25837
KW
203The L</prop_value_aliases()> function can be used to get all the synonyms
204of the category name.
205
a452d459
KW
206=item B<combining>
207
208the combining class number for I<code> used in the Canonical Ordering Algorithm.
209For Unicode 5.1, this is described in Section 3.11 C<Canonical Ordering Behavior>
210available at
211L<http://www.unicode.org/versions/Unicode5.1.0/>
212
7ef25837
KW
213The L</prop_value_aliases()> function can be used to get all the synonyms
214of the combining class number.
215
a452d459
KW
216=item B<bidi>
217
218bidirectional type of I<code>.
219This will match one of the keys in the hash returned by L</bidi_types()>.
220
7ef25837
KW
221The L</prop_value_aliases()> function can be used to get all the synonyms
222of the bidi type name.
223
a452d459
KW
224=item B<decomposition>
225
226is empty if I<code> has no decomposition; or is one or more codes
a18e976f 227(separated by spaces) that, taken in order, represent a decomposition for
a452d459
KW
228I<code>. Each has at least four hexdigits.
229The codes may be preceded by a word enclosed in angle brackets then a space,
230like C<E<lt>compatE<gt> >, giving the type of decomposition
231
06bba7d5
KW
232This decomposition may be an intermediate one whose components are also
233decomposable. Use L<Unicode::Normalize> to get the final decomposition.
234
a452d459
KW
235=item B<decimal>
236
237if I<code> is a decimal digit this is its integer numeric value
238
239=item B<digit>
240
89e4a205
KW
241if I<code> represents some other digit-like number, this is its integer
242numeric value
a452d459
KW
243
244=item B<numeric>
245
246if I<code> represents a whole or rational number, this is its numeric value.
247Rational values are expressed as a string like C<1/4>.
248
249=item B<mirrored>
250
251C<Y> or C<N> designating if I<code> is mirrored in bidirectional text
252
253=item B<unicode10>
254
255name of I<code> in the Unicode 1.0 standard if one
256existed for this code point and is different from the current name
257
258=item B<comment>
259
89e4a205 260As of Unicode 6.0, this is always empty.
a452d459
KW
261
262=item B<upper>
263
06bba7d5 264is empty if there is no single code point uppercase mapping for I<code>
4f66642e 265(its uppercase mapping is itself);
a452d459
KW
266otherwise it is that mapping expressed as at least four hexdigits.
267(L</casespec()> should be used in addition to B<charinfo()>
268for case mappings when the calling program can cope with multiple code point
269mappings.)
270
271=item B<lower>
272
06bba7d5 273is empty if there is no single code point lowercase mapping for I<code>
4f66642e 274(its lowercase mapping is itself);
a452d459
KW
275otherwise it is that mapping expressed as at least four hexdigits.
276(L</casespec()> should be used in addition to B<charinfo()>
277for case mappings when the calling program can cope with multiple code point
278mappings.)
279
280=item B<title>
281
06bba7d5 282is empty if there is no single code point titlecase mapping for I<code>
4f66642e 283(its titlecase mapping is itself);
a452d459
KW
284otherwise it is that mapping expressed as at least four hexdigits.
285(L</casespec()> should be used in addition to B<charinfo()>
286for case mappings when the calling program can cope with multiple code point
287mappings.)
288
289=item B<block>
290
a18e976f 291the block I<code> belongs to (used in C<\p{Blk=...}>).
a452d459
KW
292See L</Blocks versus Scripts>.
293
294
295=item B<script>
296
a18e976f 297the script I<code> belongs to.
a452d459
KW
298See L</Blocks versus Scripts>.
299
300=back
32c16050
JH
301
302Note that you cannot do (de)composition and casing based solely on the
a452d459
KW
303I<decomposition>, I<combining>, I<lower>, I<upper>, and I<title> fields;
304you will need also the L</compexcl()>, and L</casespec()> functions.
561c79ed
JH
305
306=cut
307
e10d7780 308# NB: This function is nearly duplicated in charnames.pm
10a6ecd2
JH
309sub _getcode {
310 my $arg = shift;
311
dc0a4417 312 if ($arg =~ /^[1-9]\d*$/) {
10a6ecd2 313 return $arg;
dc0a4417 314 } elsif ($arg =~ /^(?:[Uu]\+|0[xX])?([[:xdigit:]]+)$/) {
10a6ecd2
JH
315 return hex($1);
316 }
317
318 return;
319}
320
05dbc6f8
KW
321# Populated by _num. Converts real number back to input rational
322my %real_to_rational;
323
324# To store the contents of files found on disk.
325my @BIDIS;
326my @CATEGORIES;
327my @DECOMPOSITIONS;
328my @NUMERIC_TYPES;
5c3b35c9
KW
329my %SIMPLE_LOWER;
330my %SIMPLE_TITLE;
331my %SIMPLE_UPPER;
332my %UNICODE_1_NAMES;
72fcb9f0 333my %ISO_COMMENT;
05dbc6f8 334
05dbc6f8 335sub charinfo {
a6fa416b 336
05dbc6f8
KW
337 # This function has traditionally mimicked what is in UnicodeData.txt,
338 # warts and all. This is a re-write that avoids UnicodeData.txt so that
339 # it can be removed to save disk space. Instead, this assembles
340 # information gotten by other methods that get data from various other
341 # files. It uses charnames to get the character name; and various
342 # mktables tables.
324f9e44 343
05dbc6f8 344 use feature 'unicode_strings';
a6fa416b 345
cb3150f5
KW
346 # Will fail if called under minitest
347 use if defined &DynaLoader::boot_DynaLoader, "Unicode::Normalize" => qw(getCombinClass NFD);
348
10a6ecd2
JH
349 my $arg = shift;
350 my $code = _getcode($arg);
05dbc6f8
KW
351 croak __PACKAGE__, "::charinfo: unknown code '$arg'" unless defined $code;
352
353 # Non-unicode implies undef.
354 return if $code > 0x10FFFF;
355
356 my %prop;
357 my $char = chr($code);
358
35a865d4 359 @CATEGORIES =_read_table("To/Gc.pl") unless @CATEGORIES;
05dbc6f8
KW
360 $prop{'category'} = _search(\@CATEGORIES, 0, $#CATEGORIES, $code)
361 // $utf8::SwashInfo{'ToGc'}{'missing'};
362
363 return if $prop{'category'} eq 'Cn'; # Unassigned code points are undef
364
365 $prop{'code'} = sprintf "%04X", $code;
366 $prop{'name'} = ($char =~ /\p{Cntrl}/) ? '<control>'
367 : (charnames::viacode($code) // "");
368
369 $prop{'combining'} = getCombinClass($code);
370
35a865d4 371 @BIDIS =_read_table("To/Bc.pl") unless @BIDIS;
05dbc6f8
KW
372 $prop{'bidi'} = _search(\@BIDIS, 0, $#BIDIS, $code)
373 // $utf8::SwashInfo{'ToBc'}{'missing'};
374
375 # For most code points, we can just read in "unicore/Decomposition.pl", as
376 # its contents are exactly what should be output. But that file doesn't
377 # contain the data for the Hangul syllable decompositions, which can be
94c91ffc
KW
378 # algorithmically computed, and NFD() does that, so we call NFD() for
379 # those. We can't use NFD() for everything, as it does a complete
05dbc6f8 380 # recursive decomposition, and what this function has always done is to
94c91ffc
KW
381 # return what's in UnicodeData.txt which doesn't show that recursiveness.
382 # Fortunately, the NFD() of the Hanguls doesn't have any recursion
383 # issues.
384 # Having no decomposition implies an empty field; otherwise, all but
385 # "Canonical" imply a compatible decomposition, and the type is prefixed
386 # to that, as it is in UnicodeData.txt
9abdc62b
KW
387 UnicodeVersion() unless defined $v_unicode_version;
388 if ($v_unicode_version ge v2.0.0 && $char =~ /\p{Block=Hangul_Syllables}/) {
05dbc6f8
KW
389 # The code points of the decomposition are output in standard Unicode
390 # hex format, separated by blanks.
391 $prop{'decomposition'} = join " ", map { sprintf("%04X", $_)}
94c91ffc 392 unpack "U*", NFD($char);
a6fa416b 393 }
05dbc6f8 394 else {
35a865d4 395 @DECOMPOSITIONS = _read_table("Decomposition.pl")
05dbc6f8
KW
396 unless @DECOMPOSITIONS;
397 $prop{'decomposition'} = _search(\@DECOMPOSITIONS, 0, $#DECOMPOSITIONS,
398 $code) // "";
561c79ed 399 }
05dbc6f8
KW
400
401 # Can use num() to get the numeric values, if any.
402 if (! defined (my $value = num($char))) {
403 $prop{'decimal'} = $prop{'digit'} = $prop{'numeric'} = "";
404 }
405 else {
406 if ($char =~ /\d/) {
407 $prop{'decimal'} = $prop{'digit'} = $prop{'numeric'} = $value;
408 }
409 else {
410
411 # For non-decimal-digits, we have to read in the Numeric type
412 # to distinguish them. It is not just a matter of integer vs.
413 # rational, as some whole number values are not considered digits,
414 # e.g., TAMIL NUMBER TEN.
415 $prop{'decimal'} = "";
416
35a865d4 417 @NUMERIC_TYPES =_read_table("To/Nt.pl") unless @NUMERIC_TYPES;
05dbc6f8
KW
418 if ((_search(\@NUMERIC_TYPES, 0, $#NUMERIC_TYPES, $code) // "")
419 eq 'Digit')
420 {
421 $prop{'digit'} = $prop{'numeric'} = $value;
422 }
423 else {
424 $prop{'digit'} = "";
425 $prop{'numeric'} = $real_to_rational{$value} // $value;
426 }
427 }
428 }
429
430 $prop{'mirrored'} = ($char =~ /\p{Bidi_Mirrored}/) ? 'Y' : 'N';
431
35a865d4 432 %UNICODE_1_NAMES =_read_table("To/Na1.pl", "use_hash") unless %UNICODE_1_NAMES;
5c3b35c9 433 $prop{'unicode10'} = $UNICODE_1_NAMES{$code} // "";
05dbc6f8 434
72fcb9f0
KW
435 UnicodeVersion() unless defined $v_unicode_version;
436 if ($v_unicode_version ge v6.0.0) {
437 $prop{'comment'} = "";
438 }
439 else {
440 %ISO_COMMENT = _read_table("To/Isc.pl", "use_hash") unless %ISO_COMMENT;
441 $prop{'comment'} = (defined $ISO_COMMENT{$code})
442 ? $ISO_COMMENT{$code}
443 : "";
444 }
05dbc6f8 445
35a865d4 446 %SIMPLE_UPPER = _read_table("To/Uc.pl", "use_hash") unless %SIMPLE_UPPER;
bf7fe2df 447 $prop{'upper'} = (defined $SIMPLE_UPPER{$code})
d11155ec 448 ? sprintf("%04X", $SIMPLE_UPPER{$code})
bf7fe2df 449 : "";
75e7c50b 450
35a865d4 451 %SIMPLE_LOWER = _read_table("To/Lc.pl", "use_hash") unless %SIMPLE_LOWER;
bf7fe2df 452 $prop{'lower'} = (defined $SIMPLE_LOWER{$code})
d11155ec 453 ? sprintf("%04X", $SIMPLE_LOWER{$code})
bf7fe2df 454 : "";
75e7c50b 455
35a865d4 456 %SIMPLE_TITLE = _read_table("To/Tc.pl", "use_hash") unless %SIMPLE_TITLE;
bf7fe2df 457 $prop{'title'} = (defined $SIMPLE_TITLE{$code})
d11155ec 458 ? sprintf("%04X", $SIMPLE_TITLE{$code})
bf7fe2df 459 : "";
05dbc6f8
KW
460
461 $prop{block} = charblock($code);
462 $prop{script} = charscript($code);
463 return \%prop;
561c79ed
JH
464}
465
e882dd67
JH
466sub _search { # Binary search in a [[lo,hi,prop],[...],...] table.
467 my ($table, $lo, $hi, $code) = @_;
468
469 return if $lo > $hi;
470
471 my $mid = int(($lo+$hi) / 2);
472
473 if ($table->[$mid]->[0] < $code) {
10a6ecd2 474 if ($table->[$mid]->[1] >= $code) {
e882dd67
JH
475 return $table->[$mid]->[2];
476 } else {
477 _search($table, $mid + 1, $hi, $code);
478 }
479 } elsif ($table->[$mid]->[0] > $code) {
480 _search($table, $lo, $mid - 1, $code);
481 } else {
482 return $table->[$mid]->[2];
483 }
484}
485
cb366075 486sub _read_table ($;$) {
3a12600d
KW
487
488 # Returns the contents of the mktables generated table file located at $1
cb366075
KW
489 # in the form of either an array of arrays or a hash, depending on if the
490 # optional second parameter is true (for hash return) or not. In the case
491 # of a hash return, each key is a code point, and its corresponding value
492 # is what the table gives as the code point's corresponding value. In the
493 # case of an array return, each outer array denotes a range with [0] the
494 # start point of that range; [1] the end point; and [2] the value that
495 # every code point in the range has. The hash return is useful for fast
496 # lookup when the table contains only single code point ranges. The array
497 # return takes much less memory when there are large ranges.
3a12600d 498 #
cb366075 499 # This function has the side effect of setting
3a12600d
KW
500 # $utf8::SwashInfo{$property}{'format'} to be the mktables format of the
501 # table; and
502 # $utf8::SwashInfo{$property}{'missing'} to be the value for all entries
503 # not listed in the table.
504 # where $property is the Unicode property name, preceded by 'To' for map
505 # properties., e.g., 'ToSc'.
506 #
507 # Table entries look like one of:
508 # 0000 0040 Common # [65]
509 # 00AA Latin
510
511 my $table = shift;
cb366075
KW
512 my $return_hash = shift;
513 $return_hash = 0 unless defined $return_hash;
3a12600d 514 my @return;
cb366075 515 my %return;
3a12600d 516 local $_;
d11155ec 517 my $list = do "unicore/$table";
3a12600d 518
d11155ec
KW
519 # Look up if this property requires adjustments, which we do below if it
520 # does.
521 require "unicore/Heavy.pl";
522 my $property = $table =~ s/\.pl//r;
523 $property = $utf8::file_to_swash_name{$property};
524 my $to_adjust = defined $property
525 && $utf8::SwashInfo{$property}{'format'} eq 'a';
526
527 for (split /^/m, $list) {
3a12600d
KW
528 my ($start, $end, $value) = / ^ (.+?) \t (.*?) \t (.+?)
529 \s* ( \# .* )? # Optional comment
530 $ /x;
83fd1222
KW
531 my $decimal_start = hex $start;
532 my $decimal_end = ($end eq "") ? $decimal_start : hex $end;
cb366075 533 if ($return_hash) {
83fd1222 534 foreach my $i ($decimal_start .. $decimal_end) {
d11155ec
KW
535 $return{$i} = ($to_adjust)
536 ? $value + $i - $decimal_start
537 : $value;
cb366075
KW
538 }
539 }
d11155ec
KW
540 elsif (! $to_adjust
541 && @return
542 && $return[-1][1] == $decimal_start - 1
9a96c106
KW
543 && $return[-1][2] eq $value)
544 {
545 # If this is merely extending the previous range, do just that.
546 $return[-1]->[1] = $decimal_end;
547 }
cb366075 548 else {
83fd1222 549 push @return, [ $decimal_start, $decimal_end, $value ];
cb366075 550 }
3a12600d 551 }
cb366075 552 return ($return_hash) ? %return : @return;
3a12600d
KW
553}
554
10a6ecd2
JH
555sub charinrange {
556 my ($range, $arg) = @_;
557 my $code = _getcode($arg);
558 croak __PACKAGE__, "::charinrange: unknown code '$arg'"
559 unless defined $code;
560 _search($range, 0, $#$range, $code);
561}
562
a452d459 563=head2 B<charblock()>
561c79ed 564
55d7b906 565 use Unicode::UCD 'charblock';
561c79ed
JH
566
567 my $charblock = charblock(0x41);
10a6ecd2 568 my $charblock = charblock(1234);
a452d459 569 my $charblock = charblock(0x263a);
10a6ecd2
JH
570 my $charblock = charblock("U+263a");
571
78bf21c2 572 my $range = charblock('Armenian');
10a6ecd2 573
a452d459 574With a L</code point argument> charblock() returns the I<block> the code point
430fe03d
KW
575belongs to, e.g. C<Basic Latin>. The old-style block name is returned (see
576L</Old-style versus new-style block names>).
a452d459 577If the code point is unassigned, this returns the block it would belong to if
fe252ba7
KW
578it were assigned. (If the Unicode version being used is so early as to not
579have blocks, all code points are considered to be in C<No_Block>.)
10a6ecd2 580
78bf21c2
JH
581See also L</Blocks versus Scripts>.
582
18972f4b 583If supplied with an argument that can't be a code point, charblock() tries to
430fe03d
KW
584do the opposite and interpret the argument as an old-style block name. The
585return value
a18e976f
KW
586is a I<range set> with one range: an anonymous list with a single element that
587consists of another anonymous list whose first element is the first code point
588in the block, and whose second (and final) element is the final code point in
589the block. (The extra list consisting of just one element is so that the same
590program logic can be used to handle both this return, and the return from
591L</charscript()> which can have multiple ranges.) You can test whether a code
592point is in a range using the L</charinrange()> function. If the argument is
593not a known block, C<undef> is returned.
561c79ed 594
561c79ed
JH
595=cut
596
597my @BLOCKS;
10a6ecd2 598my %BLOCKS;
561c79ed 599
10a6ecd2 600sub _charblocks {
06bba7d5
KW
601
602 # Can't read from the mktables table because it loses the hyphens in the
603 # original.
561c79ed 604 unless (@BLOCKS) {
fe252ba7
KW
605 UnicodeVersion() unless defined $v_unicode_version;
606 if ($v_unicode_version lt v2.0.0) {
607 my $subrange = [ 0, 0x10FFFF, 'No_Block' ];
608 push @BLOCKS, $subrange;
609 push @{$BLOCKS{$3}}, $subrange;
610 }
611 elsif (openunicode(\$BLOCKSFH, "Blocks.txt")) {
6c8d78fb 612 local $_;
ce066323 613 local $/ = "\n";
10a6ecd2 614 while (<$BLOCKSFH>) {
2796c109 615 if (/^([0-9A-F]+)\.\.([0-9A-F]+);\s+(.+)/) {
10a6ecd2
JH
616 my ($lo, $hi) = (hex($1), hex($2));
617 my $subrange = [ $lo, $hi, $3 ];
618 push @BLOCKS, $subrange;
619 push @{$BLOCKS{$3}}, $subrange;
561c79ed
JH
620 }
621 }
10a6ecd2 622 close($BLOCKSFH);
561c79ed
JH
623 }
624 }
10a6ecd2
JH
625}
626
627sub charblock {
628 my $arg = shift;
629
630 _charblocks() unless @BLOCKS;
631
632 my $code = _getcode($arg);
561c79ed 633
10a6ecd2 634 if (defined $code) {
c707cf8e
KW
635 my $result = _search(\@BLOCKS, 0, $#BLOCKS, $code);
636 return $result if defined $result;
637 return 'No_Block';
638 }
639 elsif (exists $BLOCKS{$arg}) {
cb3150f5 640 return _dclone $BLOCKS{$arg};
10a6ecd2 641 }
e882dd67
JH
642}
643
a452d459 644=head2 B<charscript()>
e882dd67 645
55d7b906 646 use Unicode::UCD 'charscript';
e882dd67
JH
647
648 my $charscript = charscript(0x41);
10a6ecd2
JH
649 my $charscript = charscript(1234);
650 my $charscript = charscript("U+263a");
e882dd67 651
78bf21c2 652 my $range = charscript('Thai');
10a6ecd2 653
a452d459
KW
654With a L</code point argument> charscript() returns the I<script> the
655code point belongs to, e.g. C<Latin>, C<Greek>, C<Han>.
49ea58c8
KW
656If the code point is unassigned or the Unicode version being used is so early
657that it doesn't have scripts, this function returns C<"Unknown">.
78bf21c2 658
eb0cc9e3 659If supplied with an argument that can't be a code point, charscript() tries
a18e976f
KW
660to do the opposite and interpret the argument as a script name. The
661return value is a I<range set>: an anonymous list of lists that contain
eb0cc9e3 662I<start-of-range>, I<end-of-range> code point pairs. You can test whether a
a18e976f
KW
663code point is in a range set using the L</charinrange()> function. If the
664argument is not a known script, C<undef> is returned.
a452d459
KW
665
666See also L</Blocks versus Scripts>.
e882dd67 667
e882dd67
JH
668=cut
669
670my @SCRIPTS;
10a6ecd2 671my %SCRIPTS;
e882dd67 672
10a6ecd2 673sub _charscripts {
49ea58c8
KW
674 unless (@SCRIPTS) {
675 UnicodeVersion() unless defined $v_unicode_version;
676 if ($v_unicode_version lt v3.1.0) {
677 push @SCRIPTS, [ 0, 0x10FFFF, 'Unknown' ];
678 }
679 else {
680 @SCRIPTS =_read_table("To/Sc.pl");
681 }
682 }
7bccef0b 683 foreach my $entry (@SCRIPTS) {
f3d50ac9 684 $entry->[2] =~ s/(_\w)/\L$1/g; # Preserve old-style casing
7bccef0b 685 push @{$SCRIPTS{$entry->[2]}}, $entry;
e882dd67 686 }
10a6ecd2
JH
687}
688
689sub charscript {
690 my $arg = shift;
691
692 _charscripts() unless @SCRIPTS;
e882dd67 693
10a6ecd2
JH
694 my $code = _getcode($arg);
695
696 if (defined $code) {
7bccef0b
KW
697 my $result = _search(\@SCRIPTS, 0, $#SCRIPTS, $code);
698 return $result if defined $result;
8079ad82 699 return $utf8::SwashInfo{'ToSc'}{'missing'};
7bccef0b 700 } elsif (exists $SCRIPTS{$arg}) {
cb3150f5 701 return _dclone $SCRIPTS{$arg};
10a6ecd2 702 }
7bccef0b
KW
703
704 return;
10a6ecd2
JH
705}
706
a452d459 707=head2 B<charblocks()>
10a6ecd2 708
55d7b906 709 use Unicode::UCD 'charblocks';
10a6ecd2 710
b08cd201 711 my $charblocks = charblocks();
10a6ecd2 712
b08cd201 713charblocks() returns a reference to a hash with the known block names
a452d459 714as the keys, and the code point ranges (see L</charblock()>) as the values.
10a6ecd2 715
430fe03d
KW
716The names are in the old-style (see L</Old-style versus new-style block
717names>).
718
62b3b855
KW
719L<prop_invmap("block")|/prop_invmap()> can be used to get this same data in a
720different type of data structure.
721
78bf21c2
JH
722See also L</Blocks versus Scripts>.
723
10a6ecd2
JH
724=cut
725
726sub charblocks {
b08cd201 727 _charblocks() unless %BLOCKS;
cb3150f5 728 return _dclone \%BLOCKS;
10a6ecd2
JH
729}
730
a452d459 731=head2 B<charscripts()>
10a6ecd2 732
55d7b906 733 use Unicode::UCD 'charscripts';
10a6ecd2 734
ea508aee 735 my $charscripts = charscripts();
10a6ecd2 736
ea508aee 737charscripts() returns a reference to a hash with the known script
a452d459 738names as the keys, and the code point ranges (see L</charscript()>) as
ea508aee 739the values.
10a6ecd2 740
62b3b855
KW
741L<prop_invmap("script")|/prop_invmap()> can be used to get this same data in a
742different type of data structure.
743
78bf21c2
JH
744See also L</Blocks versus Scripts>.
745
10a6ecd2
JH
746=cut
747
748sub charscripts {
b08cd201 749 _charscripts() unless %SCRIPTS;
cb3150f5 750 return _dclone \%SCRIPTS;
561c79ed
JH
751}
752
a452d459 753=head2 B<charinrange()>
10a6ecd2 754
f200dd12 755In addition to using the C<\p{Blk=...}> and C<\P{Blk=...}> constructs, you
10a6ecd2 756can also test whether a code point is in the I<range> as returned by
a452d459
KW
757L</charblock()> and L</charscript()> or as the values of the hash returned
758by L</charblocks()> and L</charscripts()> by using charinrange():
10a6ecd2 759
55d7b906 760 use Unicode::UCD qw(charscript charinrange);
10a6ecd2
JH
761
762 $range = charscript('Hiragana');
e145285f 763 print "looks like hiragana\n" if charinrange($range, $codepoint);
10a6ecd2
JH
764
765=cut
766
ea508aee
JH
767my %GENERAL_CATEGORIES =
768 (
769 'L' => 'Letter',
770 'LC' => 'CasedLetter',
771 'Lu' => 'UppercaseLetter',
772 'Ll' => 'LowercaseLetter',
773 'Lt' => 'TitlecaseLetter',
774 'Lm' => 'ModifierLetter',
775 'Lo' => 'OtherLetter',
776 'M' => 'Mark',
777 'Mn' => 'NonspacingMark',
778 'Mc' => 'SpacingMark',
779 'Me' => 'EnclosingMark',
780 'N' => 'Number',
781 'Nd' => 'DecimalNumber',
782 'Nl' => 'LetterNumber',
783 'No' => 'OtherNumber',
784 'P' => 'Punctuation',
785 'Pc' => 'ConnectorPunctuation',
786 'Pd' => 'DashPunctuation',
787 'Ps' => 'OpenPunctuation',
788 'Pe' => 'ClosePunctuation',
789 'Pi' => 'InitialPunctuation',
790 'Pf' => 'FinalPunctuation',
791 'Po' => 'OtherPunctuation',
792 'S' => 'Symbol',
793 'Sm' => 'MathSymbol',
794 'Sc' => 'CurrencySymbol',
795 'Sk' => 'ModifierSymbol',
796 'So' => 'OtherSymbol',
797 'Z' => 'Separator',
798 'Zs' => 'SpaceSeparator',
799 'Zl' => 'LineSeparator',
800 'Zp' => 'ParagraphSeparator',
801 'C' => 'Other',
802 'Cc' => 'Control',
803 'Cf' => 'Format',
804 'Cs' => 'Surrogate',
805 'Co' => 'PrivateUse',
806 'Cn' => 'Unassigned',
807 );
808
809sub general_categories {
cb3150f5 810 return _dclone \%GENERAL_CATEGORIES;
ea508aee
JH
811}
812
a452d459 813=head2 B<general_categories()>
ea508aee
JH
814
815 use Unicode::UCD 'general_categories';
816
817 my $categories = general_categories();
818
a452d459 819This returns a reference to a hash which has short
ea508aee
JH
820general category names (such as C<Lu>, C<Nd>, C<Zs>, C<S>) as keys and long
821names (such as C<UppercaseLetter>, C<DecimalNumber>, C<SpaceSeparator>,
822C<Symbol>) as values. The hash is reversible in case you need to go
823from the long names to the short names. The general category is the
a452d459
KW
824one returned from
825L</charinfo()> under the C<category> key.
ea508aee 826
7ef25837
KW
827The L</prop_value_aliases()> function can be used to get all the synonyms of
828the category name.
829
ea508aee
JH
830=cut
831
832my %BIDI_TYPES =
833 (
834 'L' => 'Left-to-Right',
835 'LRE' => 'Left-to-Right Embedding',
836 'LRO' => 'Left-to-Right Override',
837 'R' => 'Right-to-Left',
838 'AL' => 'Right-to-Left Arabic',
839 'RLE' => 'Right-to-Left Embedding',
840 'RLO' => 'Right-to-Left Override',
841 'PDF' => 'Pop Directional Format',
842 'EN' => 'European Number',
843 'ES' => 'European Number Separator',
844 'ET' => 'European Number Terminator',
845 'AN' => 'Arabic Number',
846 'CS' => 'Common Number Separator',
847 'NSM' => 'Non-Spacing Mark',
848 'BN' => 'Boundary Neutral',
849 'B' => 'Paragraph Separator',
850 'S' => 'Segment Separator',
851 'WS' => 'Whitespace',
852 'ON' => 'Other Neutrals',
853 );
854
a452d459 855=head2 B<bidi_types()>
ea508aee
JH
856
857 use Unicode::UCD 'bidi_types';
858
859 my $categories = bidi_types();
860
a452d459 861This returns a reference to a hash which has the short
ea508aee
JH
862bidi (bidirectional) type names (such as C<L>, C<R>) as keys and long
863names (such as C<Left-to-Right>, C<Right-to-Left>) as values. The
864hash is reversible in case you need to go from the long names to the
a452d459
KW
865short names. The bidi type is the one returned from
866L</charinfo()>
ea508aee
JH
867under the C<bidi> key. For the exact meaning of the various bidi classes
868the Unicode TR9 is recommended reading:
a452d459 869L<http://www.unicode.org/reports/tr9/>
ea508aee
JH
870(as of Unicode 5.0.0)
871
7ef25837
KW
872The L</prop_value_aliases()> function can be used to get all the synonyms of
873the bidi type name.
874
ea508aee
JH
875=cut
876
a452d459 877sub bidi_types {
cb3150f5 878 return _dclone \%BIDI_TYPES;
a452d459
KW
879}
880
881=head2 B<compexcl()>
b08cd201 882
55d7b906 883 use Unicode::UCD 'compexcl';
b08cd201 884
a452d459 885 my $compexcl = compexcl(0x09dc);
b08cd201 886
2afba6a4
KW
887This routine returns C<undef> if the Unicode version being used is so early
888that it doesn't have this property. It is included for backwards
889compatibility, but as of Perl 5.12 and more modern Unicode versions, for
71a442a8
KW
890most purposes it is probably more convenient to use one of the following
891instead:
892
893 my $compexcl = chr(0x09dc) =~ /\p{Comp_Ex};
894 my $compexcl = chr(0x09dc) =~ /\p{Full_Composition_Exclusion};
895
896or even
897
898 my $compexcl = chr(0x09dc) =~ /\p{CE};
899 my $compexcl = chr(0x09dc) =~ /\p{Composition_Exclusion};
900
901The first two forms return B<true> if the L</code point argument> should not
76b05678
KW
902be produced by composition normalization. For the final two forms to return
903B<true>, it is additionally required that this fact not otherwise be
904determinable from the Unicode data base.
71a442a8
KW
905
906This routine behaves identically to the final two forms. That is,
907it does not return B<true> if the code point has a decomposition
a452d459
KW
908consisting of another single code point, nor if its decomposition starts
909with a code point whose combining class is non-zero. Code points that meet
910either of these conditions should also not be produced by composition
71a442a8
KW
911normalization, which is probably why you should use the
912C<Full_Composition_Exclusion> property instead, as shown above.
b08cd201 913
71a442a8 914The routine returns B<false> otherwise.
b08cd201
JH
915
916=cut
917
b08cd201
JH
918sub compexcl {
919 my $arg = shift;
920 my $code = _getcode($arg);
74f8133e
JH
921 croak __PACKAGE__, "::compexcl: unknown code '$arg'"
922 unless defined $code;
b08cd201 923
2afba6a4
KW
924 UnicodeVersion() unless defined $v_unicode_version;
925 return if $v_unicode_version lt v3.0.0;
926
36c2430c 927 no warnings "non_unicode"; # So works on non-Unicode code points
71a442a8 928 return chr($code) =~ /\p{Composition_Exclusion}/;
b08cd201
JH
929}
930
a452d459 931=head2 B<casefold()>
b08cd201 932
55d7b906 933 use Unicode::UCD 'casefold';
b08cd201 934
a452d459
KW
935 my $casefold = casefold(0xDF);
936 if (defined $casefold) {
937 my @full_fold_hex = split / /, $casefold->{'full'};
938 my $full_fold_string =
939 join "", map {chr(hex($_))} @full_fold_hex;
940 my @turkic_fold_hex =
941 split / /, ($casefold->{'turkic'} ne "")
942 ? $casefold->{'turkic'}
943 : $casefold->{'full'};
944 my $turkic_fold_string =
945 join "", map {chr(hex($_))} @turkic_fold_hex;
946 }
947 if (defined $casefold && $casefold->{'simple'} ne "") {
948 my $simple_fold_hex = $casefold->{'simple'};
949 my $simple_fold_string = chr(hex($simple_fold_hex));
950 }
b08cd201 951
a452d459 952This returns the (almost) locale-independent case folding of the
6329003c
KW
953character specified by the L</code point argument>. (Starting in Perl v5.16,
954the core function C<fc()> returns the C<full> mapping (described below)
955faster than this does, and for entire strings.)
b08cd201 956
6329003c 957If there is no case folding for the input code point, C<undef> is returned.
a452d459
KW
958
959If there is a case folding for that code point, a reference to a hash
b08cd201
JH
960with the following fields is returned:
961
a452d459
KW
962=over
963
964=item B<code>
965
966the input L</code point argument> expressed in hexadecimal, with leading zeros
967added if necessary to make it contain at least four hexdigits
968
969=item B<full>
970
a18e976f 971one or more codes (separated by spaces) that, taken in order, give the
a452d459
KW
972code points for the case folding for I<code>.
973Each has at least four hexdigits.
974
975=item B<simple>
976
977is empty, or is exactly one code with at least four hexdigits which can be used
978as an alternative case folding when the calling program cannot cope with the
979fold being a sequence of multiple code points. If I<full> is just one code
980point, then I<simple> equals I<full>. If there is no single code point folding
981defined for I<code>, then I<simple> is the empty string. Otherwise, it is an
982inferior, but still better-than-nothing alternative folding to I<full>.
983
984=item B<mapping>
985
986is the same as I<simple> if I<simple> is not empty, and it is the same as I<full>
987otherwise. It can be considered to be the simplest possible folding for
988I<code>. It is defined primarily for backwards compatibility.
989
990=item B<status>
b08cd201 991
a452d459
KW
992is C<C> (for C<common>) if the best possible fold is a single code point
993(I<simple> equals I<full> equals I<mapping>). It is C<S> if there are distinct
994folds, I<simple> and I<full> (I<mapping> equals I<simple>). And it is C<F> if
a18e976f
KW
995there is only a I<full> fold (I<mapping> equals I<full>; I<simple> is empty).
996Note that this
a452d459
KW
997describes the contents of I<mapping>. It is defined primarily for backwards
998compatibility.
b08cd201 999
6329003c 1000For Unicode versions between 3.1 and 3.1.1 inclusive, I<status> can also be
a452d459
KW
1001C<I> which is the same as C<C> but is a special case for dotted uppercase I and
1002dotless lowercase i:
b08cd201 1003
a452d459 1004=over
b08cd201 1005
a18e976f 1006=item B<*> If you use this C<I> mapping
a452d459 1007
a18e976f 1008the result is case-insensitive,
a452d459
KW
1009but dotless and dotted I's are not distinguished
1010
a18e976f 1011=item B<*> If you exclude this C<I> mapping
a452d459 1012
a18e976f 1013the result is not fully case-insensitive, but
a452d459
KW
1014dotless and dotted I's are distinguished
1015
1016=back
1017
1018=item B<turkic>
1019
1020contains any special folding for Turkic languages. For versions of Unicode
1021starting with 3.2, this field is empty unless I<code> has a different folding
1022in Turkic languages, in which case it is one or more codes (separated by
a18e976f 1023spaces) that, taken in order, give the code points for the case folding for
a452d459
KW
1024I<code> in those languages.
1025Each code has at least four hexdigits.
1026Note that this folding does not maintain canonical equivalence without
1027additional processing.
1028
6329003c
KW
1029For Unicode versions between 3.1 and 3.1.1 inclusive, this field is empty unless
1030there is a
a452d459
KW
1031special folding for Turkic languages, in which case I<status> is C<I>, and
1032I<mapping>, I<full>, I<simple>, and I<turkic> are all equal.
1033
1034=back
1035
1036Programs that want complete generality and the best folding results should use
1037the folding contained in the I<full> field. But note that the fold for some
1038code points will be a sequence of multiple code points.
1039
1040Programs that can't cope with the fold mapping being multiple code points can
1041use the folding contained in the I<simple> field, with the loss of some
1042generality. In Unicode 5.1, about 7% of the defined foldings have no single
1043code point folding.
1044
1045The I<mapping> and I<status> fields are provided for backwards compatibility for
1046existing programs. They contain the same values as in previous versions of
1047this function.
1048
1049Locale is not completely independent. The I<turkic> field contains results to
1050use when the locale is a Turkic language.
b08cd201
JH
1051
1052For more information about case mappings see
a452d459 1053L<http://www.unicode.org/unicode/reports/tr21>
b08cd201
JH
1054
1055=cut
1056
1057my %CASEFOLD;
1058
1059sub _casefold {
727c62ff
KW
1060 unless (%CASEFOLD) { # Populate the hash
1061 my ($full_invlist_ref, $full_invmap_ref, undef, $default)
1062 = prop_invmap('Case_Folding');
1063
1064 # Use the recipe given in the prop_invmap() pod to convert the
1065 # inversion map into the hash.
1066 for my $i (0 .. @$full_invlist_ref - 1 - 1) {
1067 next if $full_invmap_ref->[$i] == $default;
1068 my $adjust = -1;
1069 for my $j ($full_invlist_ref->[$i] .. $full_invlist_ref->[$i+1] -1) {
1070 $adjust++;
1071 if (! ref $full_invmap_ref->[$i]) {
1072
1073 # This is a single character mapping
1074 $CASEFOLD{$j}{'status'} = 'C';
1075 $CASEFOLD{$j}{'simple'}
1076 = $CASEFOLD{$j}{'full'}
1077 = $CASEFOLD{$j}{'mapping'}
1078 = sprintf("%04X", $full_invmap_ref->[$i] + $adjust);
1079 $CASEFOLD{$j}{'code'} = sprintf("%04X", $j);
1080 $CASEFOLD{$j}{'turkic'} = "";
1081 }
1082 else { # prop_invmap ensures that $adjust is 0 for a ref
1083 $CASEFOLD{$j}{'status'} = 'F';
1084 $CASEFOLD{$j}{'full'}
1085 = $CASEFOLD{$j}{'mapping'}
1086 = join " ", map { sprintf "%04X", $_ }
1087 @{$full_invmap_ref->[$i]};
1088 $CASEFOLD{$j}{'simple'} = "";
1089 $CASEFOLD{$j}{'code'} = sprintf("%04X", $j);
1090 $CASEFOLD{$j}{'turkic'} = "";
1091 }
1092 }
1093 }
1094
1095 # We have filled in the full mappings above, assuming there were no
1096 # simple ones for the ones with multi-character maps. Now, we find
1097 # and fix the cases where that assumption was false.
1098 (my ($simple_invlist_ref, $simple_invmap_ref, undef), $default)
1099 = prop_invmap('Simple_Case_Folding');
1100 for my $i (0 .. @$simple_invlist_ref - 1 - 1) {
1101 next if $simple_invmap_ref->[$i] == $default;
1102 my $adjust = -1;
1103 for my $j ($simple_invlist_ref->[$i]
1104 .. $simple_invlist_ref->[$i+1] -1)
1105 {
1106 $adjust++;
1107 next if $CASEFOLD{$j}{'status'} eq 'C';
1108 $CASEFOLD{$j}{'status'} = 'S';
1109 $CASEFOLD{$j}{'simple'}
1110 = $CASEFOLD{$j}{'mapping'}
1111 = sprintf("%04X", $simple_invmap_ref->[$i] + $adjust);
1112 $CASEFOLD{$j}{'code'} = sprintf("%04X", $j);
1113 $CASEFOLD{$j}{'turkic'} = "";
1114 }
1115 }
1116
1117 # We hard-code in the turkish rules
1118 UnicodeVersion() unless defined $v_unicode_version;
1119 if ($v_unicode_version ge v3.2.0) {
1120
1121 # These two code points should already have regular entries, so
1122 # just fill in the turkish fields
1123 $CASEFOLD{ord('I')}{'turkic'} = '0131';
1124 $CASEFOLD{0x130}{'turkic'} = sprintf "%04X", ord('i');
1125 }
1126 elsif ($v_unicode_version ge v3.1.0) {
1127
1128 # These two code points don't have entries otherwise.
1129 $CASEFOLD{0x130}{'code'} = '0130';
1130 $CASEFOLD{0x131}{'code'} = '0131';
1131 $CASEFOLD{0x130}{'status'} = $CASEFOLD{0x131}{'status'} = 'I';
1132 $CASEFOLD{0x130}{'turkic'}
1133 = $CASEFOLD{0x130}{'mapping'}
1134 = $CASEFOLD{0x130}{'full'}
1135 = $CASEFOLD{0x130}{'simple'}
1136 = $CASEFOLD{0x131}{'turkic'}
1137 = $CASEFOLD{0x131}{'mapping'}
1138 = $CASEFOLD{0x131}{'full'}
1139 = $CASEFOLD{0x131}{'simple'}
1140 = sprintf "%04X", ord('i');
1141 }
b08cd201
JH
1142 }
1143}
1144
1145sub casefold {
1146 my $arg = shift;
1147 my $code = _getcode($arg);
74f8133e
JH
1148 croak __PACKAGE__, "::casefold: unknown code '$arg'"
1149 unless defined $code;
b08cd201
JH
1150
1151 _casefold() unless %CASEFOLD;
1152
1153 return $CASEFOLD{$code};
1154}
1155
a452d459 1156=head2 B<casespec()>
b08cd201 1157
55d7b906 1158 use Unicode::UCD 'casespec';
b08cd201 1159
a452d459 1160 my $casespec = casespec(0xFB00);
b08cd201 1161
a452d459
KW
1162This returns the potentially locale-dependent case mappings of the L</code point
1163argument>. The mappings may be longer than a single code point (which the basic
1164Unicode case mappings as returned by L</charinfo()> never are).
b08cd201 1165
a452d459
KW
1166If there are no case mappings for the L</code point argument>, or if all three
1167possible mappings (I<lower>, I<title> and I<upper>) result in single code
a18e976f 1168points and are locale independent and unconditional, C<undef> is returned
5d8e6e41
KW
1169(which means that the case mappings, if any, for the code point are those
1170returned by L</charinfo()>).
a452d459
KW
1171
1172Otherwise, a reference to a hash giving the mappings (or a reference to a hash
5d8e6e41
KW
1173of such hashes, explained below) is returned with the following keys and their
1174meanings:
a452d459
KW
1175
1176The keys in the bottom layer hash with the meanings of their values are:
1177
1178=over
1179
1180=item B<code>
1181
1182the input L</code point argument> expressed in hexadecimal, with leading zeros
1183added if necessary to make it contain at least four hexdigits
1184
1185=item B<lower>
1186
a18e976f 1187one or more codes (separated by spaces) that, taken in order, give the
a452d459
KW
1188code points for the lower case of I<code>.
1189Each has at least four hexdigits.
1190
1191=item B<title>
b08cd201 1192
a18e976f 1193one or more codes (separated by spaces) that, taken in order, give the
a452d459
KW
1194code points for the title case of I<code>.
1195Each has at least four hexdigits.
b08cd201 1196
d2da20e3 1197=item B<upper>
b08cd201 1198
a18e976f 1199one or more codes (separated by spaces) that, taken in order, give the
a452d459
KW
1200code points for the upper case of I<code>.
1201Each has at least four hexdigits.
1202
1203=item B<condition>
1204
1205the conditions for the mappings to be valid.
a18e976f 1206If C<undef>, the mappings are always valid.
a452d459
KW
1207When defined, this field is a list of conditions,
1208all of which must be true for the mappings to be valid.
1209The list consists of one or more
1210I<locales> (see below)
1211and/or I<contexts> (explained in the next paragraph),
1212separated by spaces.
1213(Other than as used to separate elements, spaces are to be ignored.)
1214Case distinctions in the condition list are not significant.
82c0b05b 1215Conditions preceded by "NON_" represent the negation of the condition.
b08cd201 1216
a452d459
KW
1217A I<context> is one of those defined in the Unicode standard.
1218For Unicode 5.1, they are defined in Section 3.13 C<Default Case Operations>
1219available at
5d8e6e41
KW
1220L<http://www.unicode.org/versions/Unicode5.1.0/>.
1221These are for context-sensitive casing.
f499c386 1222
a452d459
KW
1223=back
1224
5d8e6e41 1225The hash described above is returned for locale-independent casing, where
a18e976f 1226at least one of the mappings has length longer than one. If C<undef> is
5d8e6e41
KW
1227returned, the code point may have mappings, but if so, all are length one,
1228and are returned by L</charinfo()>.
1229Note that when this function does return a value, it will be for the complete
1230set of mappings for a code point, even those whose length is one.
1231
1232If there are additional casing rules that apply only in certain locales,
1233an additional key for each will be defined in the returned hash. Each such key
1234will be its locale name, defined as a 2-letter ISO 3166 country code, possibly
1235followed by a "_" and a 2-letter ISO language code (possibly followed by a "_"
1236and a variant code). You can find the lists of all possible locales, see
1237L<Locale::Country> and L<Locale::Language>.
89e4a205 1238(In Unicode 6.0, the only locales returned by this function
a452d459 1239are C<lt>, C<tr>, and C<az>.)
b08cd201 1240
5d8e6e41
KW
1241Each locale key is a reference to a hash that has the form above, and gives
1242the casing rules for that particular locale, which take precedence over the
1243locale-independent ones when in that locale.
1244
1245If the only casing for a code point is locale-dependent, then the returned
1246hash will not have any of the base keys, like C<code>, C<upper>, etc., but
1247will contain only locale keys.
1248
b08cd201 1249For more information about case mappings see
a452d459 1250L<http://www.unicode.org/unicode/reports/tr21/>
b08cd201
JH
1251
1252=cut
1253
1254my %CASESPEC;
1255
1256sub _casespec {
1257 unless (%CASESPEC) {
551b6b6f 1258 if (openunicode(\$CASESPECFH, "SpecialCasing.txt")) {
6c8d78fb 1259 local $_;
ce066323 1260 local $/ = "\n";
b08cd201
JH
1261 while (<$CASESPECFH>) {
1262 if (/^([0-9A-F]+); ([0-9A-F]+(?: [0-9A-F]+)*)?; ([0-9A-F]+(?: [0-9A-F]+)*)?; ([0-9A-F]+(?: [0-9A-F]+)*)?; (\w+(?: \w+)*)?/) {
f499c386
JH
1263 my ($hexcode, $lower, $title, $upper, $condition) =
1264 ($1, $2, $3, $4, $5);
1265 my $code = hex($hexcode);
1266 if (exists $CASESPEC{$code}) {
1267 if (exists $CASESPEC{$code}->{code}) {
1268 my ($oldlower,
1269 $oldtitle,
1270 $oldupper,
1271 $oldcondition) =
1272 @{$CASESPEC{$code}}{qw(lower
1273 title
1274 upper
1275 condition)};
822ebcc8
JH
1276 if (defined $oldcondition) {
1277 my ($oldlocale) =
f499c386 1278 ($oldcondition =~ /^([a-z][a-z](?:_\S+)?)/);
f499c386
JH
1279 delete $CASESPEC{$code};
1280 $CASESPEC{$code}->{$oldlocale} =
1281 { code => $hexcode,
1282 lower => $oldlower,
1283 title => $oldtitle,
1284 upper => $oldupper,
1285 condition => $oldcondition };
f499c386
JH
1286 }
1287 }
1288 my ($locale) =
1289 ($condition =~ /^([a-z][a-z](?:_\S+)?)/);
1290 $CASESPEC{$code}->{$locale} =
1291 { code => $hexcode,
1292 lower => $lower,
1293 title => $title,
1294 upper => $upper,
1295 condition => $condition };
1296 } else {
1297 $CASESPEC{$code} =
1298 { code => $hexcode,
1299 lower => $lower,
1300 title => $title,
1301 upper => $upper,
1302 condition => $condition };
1303 }
b08cd201
JH
1304 }
1305 }
1306 close($CASESPECFH);
1307 }
1308 }
1309}
1310
1311sub casespec {
1312 my $arg = shift;
1313 my $code = _getcode($arg);
74f8133e
JH
1314 croak __PACKAGE__, "::casespec: unknown code '$arg'"
1315 unless defined $code;
b08cd201
JH
1316
1317 _casespec() unless %CASESPEC;
1318
cb3150f5 1319 return ref $CASESPEC{$code} ? _dclone $CASESPEC{$code} : $CASESPEC{$code};
b08cd201
JH
1320}
1321
a452d459 1322=head2 B<namedseq()>
a2bd7410
JH
1323
1324 use Unicode::UCD 'namedseq';
1325
1326 my $namedseq = namedseq("KATAKANA LETTER AINU P");
1327 my @namedseq = namedseq("KATAKANA LETTER AINU P");
1328 my %namedseq = namedseq();
1329
1330If used with a single argument in a scalar context, returns the string
a18e976f 1331consisting of the code points of the named sequence, or C<undef> if no
a2bd7410 1332named sequence by that name exists. If used with a single argument in
956cae9a
KW
1333a list context, it returns the list of the ordinals of the code points. If used
1334with no
a2bd7410
JH
1335arguments in a list context, returns a hash with the names of the
1336named sequences as the keys and the named sequences as strings as
a18e976f 1337the values. Otherwise, it returns C<undef> or an empty list depending
a2bd7410
JH
1338on the context.
1339
a452d459
KW
1340This function only operates on officially approved (not provisional) named
1341sequences.
a2bd7410 1342
27f853a0
KW
1343Note that as of Perl 5.14, C<\N{KATAKANA LETTER AINU P}> will insert the named
1344sequence into double-quoted strings, and C<charnames::string_vianame("KATAKANA
1345LETTER AINU P")> will return the same string this function does, but will also
1346operate on character names that aren't named sequences, without you having to
1347know which are which. See L<charnames>.
1348
a2bd7410
JH
1349=cut
1350
1351my %NAMEDSEQ;
1352
1353sub _namedseq {
1354 unless (%NAMEDSEQ) {
98ef7649 1355 if (openunicode(\$NAMEDSEQFH, "Name.pl")) {
a2bd7410 1356 local $_;
ce066323 1357 local $/ = "\n";
a2bd7410 1358 while (<$NAMEDSEQFH>) {
98ef7649
KW
1359 if (/^ [0-9A-F]+ \ /x) {
1360 chomp;
1361 my ($sequence, $name) = split /\t/;
1362 my @s = map { chr(hex($_)) } split(' ', $sequence);
1363 $NAMEDSEQ{$name} = join("", @s);
a2bd7410
JH
1364 }
1365 }
1366 close($NAMEDSEQFH);
1367 }
1368 }
1369}
1370
1371sub namedseq {
98ef7649
KW
1372
1373 # Use charnames::string_vianame() which now returns this information,
1374 # unless the caller wants the hash returned, in which case we read it in,
1375 # and thereafter use it instead of calling charnames, as it is faster.
1376
a2bd7410
JH
1377 my $wantarray = wantarray();
1378 if (defined $wantarray) {
1379 if ($wantarray) {
1380 if (@_ == 0) {
98ef7649 1381 _namedseq() unless %NAMEDSEQ;
a2bd7410
JH
1382 return %NAMEDSEQ;
1383 } elsif (@_ == 1) {
98ef7649
KW
1384 my $s;
1385 if (%NAMEDSEQ) {
1386 $s = $NAMEDSEQ{ $_[0] };
1387 }
1388 else {
1389 $s = charnames::string_vianame($_[0]);
1390 }
a2bd7410
JH
1391 return defined $s ? map { ord($_) } split('', $s) : ();
1392 }
1393 } elsif (@_ == 1) {
98ef7649
KW
1394 return $NAMEDSEQ{ $_[0] } if %NAMEDSEQ;
1395 return charnames::string_vianame($_[0]);
a2bd7410
JH
1396 }
1397 }
1398 return;
1399}
1400
7319f91d
KW
1401my %NUMERIC;
1402
1403sub _numeric {
35a865d4 1404 my @numbers = _read_table("To/Nv.pl");
98025745
KW
1405 foreach my $entry (@numbers) {
1406 my ($start, $end, $value) = @$entry;
1407
05dbc6f8
KW
1408 # If value contains a slash, convert to decimal, add a reverse hash
1409 # used by charinfo.
98025745
KW
1410 if ((my @rational = split /\//, $value) == 2) {
1411 my $real = $rational[0] / $rational[1];
05dbc6f8 1412 $real_to_rational{$real} = $value;
98025745 1413 $value = $real;
98025745 1414
4f143a72
KW
1415 # Should only be single element, but just in case...
1416 for my $i ($start .. $end) {
1417 $NUMERIC{$i} = $value;
1418 }
1419 }
1420 else {
1421 # The values require adjusting, as is in 'a' format
1422 for my $i ($start .. $end) {
1423 $NUMERIC{$i} = $value + $i - $start;
1424 }
7319f91d 1425 }
7319f91d 1426 }
2dc5eb26
KW
1427
1428 # Decided unsafe to use these that aren't officially part of the Unicode
1429 # standard.
1430 #use Math::Trig;
1431 #my $pi = acos(-1.0);
98025745 1432 #$NUMERIC{0x03C0} = $pi;
7319f91d
KW
1433
1434 # Euler's constant, not to be confused with Euler's number
98025745 1435 #$NUMERIC{0x2107} = 0.57721566490153286060651209008240243104215933593992;
7319f91d
KW
1436
1437 # Euler's number
98025745 1438 #$NUMERIC{0x212F} = 2.7182818284590452353602874713526624977572;
2dc5eb26 1439
7319f91d
KW
1440 return;
1441}
1442
1443=pod
1444
67592e11 1445=head2 B<num()>
7319f91d 1446
eefd7bc2
KW
1447 use Unicode::UCD 'num';
1448
1449 my $val = num("123");
1450 my $one_quarter = num("\N{VULGAR FRACTION 1/4}");
1451
7319f91d
KW
1452C<num> returns the numeric value of the input Unicode string; or C<undef> if it
1453doesn't think the entire string has a completely valid, safe numeric value.
1454
1455If the string is just one character in length, the Unicode numeric value
1456is returned if it has one, or C<undef> otherwise. Note that this need
1457not be a whole number. C<num("\N{TIBETAN DIGIT HALF ZERO}")>, for
2dc5eb26
KW
1458example returns -0.5.
1459
1460=cut
7319f91d 1461
2dc5eb26
KW
1462#A few characters to which Unicode doesn't officially
1463#assign a numeric value are considered numeric by C<num>.
1464#These are:
1465
1466# EULER CONSTANT 0.5772... (this is NOT Euler's number)
1467# SCRIPT SMALL E 2.71828... (this IS Euler's number)
1468# GREEK SMALL LETTER PI 3.14159...
1469
1470=pod
7319f91d
KW
1471
1472If the string is more than one character, C<undef> is returned unless
8bb4c8e2 1473all its characters are decimal digits (that is, they would match C<\d+>),
7319f91d
KW
1474from the same script. For example if you have an ASCII '0' and a Bengali
1475'3', mixed together, they aren't considered a valid number, and C<undef>
1476is returned. A further restriction is that the digits all have to be of
1477the same form. A half-width digit mixed with a full-width one will
1478return C<undef>. The Arabic script has two sets of digits; C<num> will
1479return C<undef> unless all the digits in the string come from the same
1480set.
1481
1482C<num> errs on the side of safety, and there may be valid strings of
1483decimal digits that it doesn't recognize. Note that Unicode defines
1484a number of "digit" characters that aren't "decimal digit" characters.
a278d14b 1485"Decimal digits" have the property that they have a positional value, i.e.,
7319f91d
KW
1486there is a units position, a 10's position, a 100's, etc, AND they are
1487arranged in Unicode in blocks of 10 contiguous code points. The Chinese
1488digits, for example, are not in such a contiguous block, and so Unicode
1489doesn't view them as decimal digits, but merely digits, and so C<\d> will not
1490match them. A single-character string containing one of these digits will
1491have its decimal value returned by C<num>, but any longer string containing
1492only these digits will return C<undef>.
1493
a278d14b
KW
1494Strings of multiple sub- and superscripts are not recognized as numbers. You
1495can use either of the compatibility decompositions in Unicode::Normalize to
7319f91d
KW
1496change these into digits, and then call C<num> on the result.
1497
1498=cut
1499
1500# To handle sub, superscripts, this could if called in list context,
1501# consider those, and return the <decomposition> type in the second
1502# array element.
1503
1504sub num {
1505 my $string = $_[0];
1506
1507 _numeric unless %NUMERIC;
1508
1509 my $length = length($string);
98025745 1510 return $NUMERIC{ord($string)} if $length == 1;
7319f91d
KW
1511 return if $string =~ /\D/;
1512 my $first_ord = ord(substr($string, 0, 1));
98025745 1513 my $value = $NUMERIC{$first_ord};
5522af1c
KW
1514
1515 # To be a valid decimal number, it should be in a block of 10 consecutive
1516 # characters, whose values are 0, 1, 2, ... 9. Therefore this digit's
1517 # value is its offset in that block from the character that means zero.
7319f91d
KW
1518 my $zero_ord = $first_ord - $value;
1519
5522af1c
KW
1520 # Unicode 6.0 instituted the rule that only digits in a consecutive
1521 # block of 10 would be considered decimal digits. If this is an earlier
1522 # release, we verify that this first character is a member of such a
1523 # block. That is, that the block of characters surrounding this one
1524 # consists of all \d characters whose numeric values are the expected
1525 # ones.
1526 UnicodeVersion() unless defined $v_unicode_version;
1527 if ($v_unicode_version lt v6.0.0) {
1528 for my $i (0 .. 9) {
1529 my $ord = $zero_ord + $i;
1530 return unless chr($ord) =~ /\d/;
1531 my $numeric = $NUMERIC{$ord};
1532 return unless defined $numeric;
1533 return unless $numeric == $i;
1534 }
1535 }
1536
7319f91d 1537 for my $i (1 .. $length -1) {
5522af1c
KW
1538
1539 # Here we know either by verifying, or by fact of the first character
1540 # being a \d in Unicode 6.0 or later, that any character between the
1541 # character that means 0, and 9 positions above it must be \d, and
1542 # must have its value correspond to its offset from the zero. Any
1543 # characters outside these 10 do not form a legal number for this
1544 # function.
7319f91d
KW
1545 my $ord = ord(substr($string, $i, 1));
1546 my $digit = $ord - $zero_ord;
1547 return unless $digit >= 0 && $digit <= 9;
1548 $value = $value * 10 + $digit;
1549 }
5522af1c 1550
7319f91d
KW
1551 return $value;
1552}
1553
7ef25837
KW
1554=pod
1555
1556=head2 B<prop_aliases()>
1557
1558 use Unicode::UCD 'prop_aliases';
1559
1560 my ($short_name, $full_name, @other_names) = prop_aliases("space");
1561 my $same_full_name = prop_aliases("Space"); # Scalar context
1562 my ($same_short_name) = prop_aliases("Space"); # gets 0th element
1563 print "The full name is $full_name\n";
1564 print "The short name is $short_name\n";
1565 print "The other aliases are: ", join(", ", @other_names), "\n";
1566
1567 prints:
1568 The full name is White_Space
1569 The short name is WSpace
1570 The other aliases are: Space
1571
1572Most Unicode properties have several synonymous names. Typically, there is at
1573least a short name, convenient to type, and a long name that more fully
1574describes the property, and hence is more easily understood.
1575
1576If you know one name for a Unicode property, you can use C<prop_aliases> to find
1577either the long name (when called in scalar context), or a list of all of the
1578names, somewhat ordered so that the short name is in the 0th element, the long
1579name in the next element, and any other synonyms are in the remaining
1580elements, in no particular order.
1581
1582The long name is returned in a form nicely capitalized, suitable for printing.
1583
1584The input parameter name is loosely matched, which means that white space,
1585hyphens, and underscores are ignored (except for the trailing underscore in
1586the old_form grandfathered-in C<"L_">, which is better written as C<"LC">, and
1587both of which mean C<General_Category=Cased Letter>).
1588
1589If the name is unknown, C<undef> is returned (or an empty list in list
1590context). Note that Perl typically recognizes property names in regular
1591expressions with an optional C<"Is_>" (with or without the underscore)
1592prefixed to them, such as C<\p{isgc=punct}>. This function does not recognize
1593those in the input, returning C<undef>. Nor are they included in the output
1594as possible synonyms.
1595
1596C<prop_aliases> does know about the Perl extensions to Unicode properties,
1597such as C<Any> and C<XPosixAlpha>, and the single form equivalents to Unicode
1598properties such as C<XDigit>, C<Greek>, C<In_Greek>, and C<Is_Greek>. The
1599final example demonstrates that the C<"Is_"> prefix is recognized for these
1600extensions; it is needed to resolve ambiguities. For example,
1601C<prop_aliases('lc')> returns the list C<(lc, Lowercase_Mapping)>, but
1602C<prop_aliases('islc')> returns C<(Is_LC, Cased_Letter)>. This is
1603because C<islc> is a Perl extension which is short for
1604C<General_Category=Cased Letter>. The lists returned for the Perl extensions
1605will not include the C<"Is_"> prefix (whether or not the input had it) unless
1606needed to resolve ambiguities, as shown in the C<"islc"> example, where the
1607returned list had one element containing C<"Is_">, and the other without.
1608
1609It is also possible for the reverse to happen: C<prop_aliases('isc')> returns
1610the list C<(isc, ISO_Comment)>; whereas C<prop_aliases('c')> returns
1611C<(C, Other)> (the latter being a Perl extension meaning
ee94c7d1
KW
1612C<General_Category=Other>.
1613L<perluniprops/Properties accessible through Unicode::UCD> lists the available
1614forms, including which ones are discouraged from use.
7ef25837
KW
1615
1616Those discouraged forms are accepted as input to C<prop_aliases>, but are not
1617returned in the lists. C<prop_aliases('isL&')> and C<prop_aliases('isL_')>,
1618which are old synonyms for C<"Is_LC"> and should not be used in new code, are
1619examples of this. These both return C<(Is_LC, Cased_Letter)>. Thus this
1620function allows you to take a discourarged form, and find its acceptable
1621alternatives. The same goes with single-form Block property equivalences.
1622Only the forms that begin with C<"In_"> are not discouraged; if you pass
1623C<prop_aliases> a discouraged form, you will get back the equivalent ones that
1624begin with C<"In_">. It will otherwise look like a new-style block name (see.
1625L</Old-style versus new-style block names>).
1626
1627C<prop_aliases> does not know about any user-defined properties, and will
1628return C<undef> if called with one of those. Likewise for Perl internal
1629properties, with the exception of "Perl_Decimal_Digit" which it does know
1630about (and which is documented below in L</prop_invmap()>).
1631
1632=cut
1633
1634# It may be that there are use cases where the discouraged forms should be
1635# returned. If that comes up, an optional boolean second parameter to the
1636# function could be created, for example.
1637
1638# These are created by mktables for this routine and stored in unicore/UCD.pl
1639# where their structures are described.
1640our %string_property_loose_to_name;
1641our %ambiguous_names;
1642our %loose_perlprop_to_name;
1643our %prop_aliases;
1644
1645sub prop_aliases ($) {
1646 my $prop = $_[0];
1647 return unless defined $prop;
1648
1649 require "unicore/UCD.pl";
1650 require "unicore/Heavy.pl";
1651 require "utf8_heavy.pl";
1652
1653 # The property name may be loosely or strictly matched; we don't know yet.
1654 # But both types use lower-case.
1655 $prop = lc $prop;
1656
1657 # It is loosely matched if its lower case isn't known to be strict.
1658 my $list_ref;
1659 if (! exists $utf8::stricter_to_file_of{$prop}) {
1660 my $loose = utf8::_loose_name($prop);
1661
1662 # There is a hash that converts from any loose name to its standard
1663 # form, mapping all synonyms for a name to one name that can be used
1664 # as a key into another hash. The whole concept is for memory
1665 # savings, as the second hash doesn't have to have all the
1666 # combinations. Actually, there are two hashes that do the
1667 # converstion. One is used in utf8_heavy.pl (stored in Heavy.pl) for
1668 # looking up properties matchable in regexes. This function needs to
1669 # access string properties, which aren't available in regexes, so a
1670 # second conversion hash is made for them (stored in UCD.pl). Look in
1671 # the string one now, as the rest can have an optional 'is' prefix,
1672 # which these don't.
1673 if (exists $string_property_loose_to_name{$loose}) {
1674
1675 # Convert to its standard loose name.
1676 $prop = $string_property_loose_to_name{$loose};
1677 }
1678 else {
1679 my $retrying = 0; # bool. ? Has an initial 'is' been stripped
1680 RETRY:
1681 if (exists $utf8::loose_property_name_of{$loose}
1682 && (! $retrying
1683 || ! exists $ambiguous_names{$loose}))
1684 {
1685 # Found an entry giving the standard form. We don't get here
1686 # (in the test above) when we've stripped off an
1687 # 'is' and the result is an ambiguous name. That is because
1688 # these are official Unicode properties (though Perl can have
1689 # an optional 'is' prefix meaning the official property), and
1690 # all ambiguous cases involve a Perl single-form extension
1691 # for the gc, script, or block properties, and the stripped
1692 # 'is' means that they mean one of those, and not one of
1693 # these
1694 $prop = $utf8::loose_property_name_of{$loose};
1695 }
1696 elsif (exists $loose_perlprop_to_name{$loose}) {
1697
1698 # This hash is specifically for this function to list Perl
1699 # extensions that aren't in the earlier hashes. If there is
1700 # only one element, the short and long names are identical.
1701 # Otherwise the form is already in the same form as
1702 # %prop_aliases, which is handled at the end of the function.
1703 $list_ref = $loose_perlprop_to_name{$loose};
1704 if (@$list_ref == 1) {
1705 my @list = ($list_ref->[0], $list_ref->[0]);
1706 $list_ref = \@list;
1707 }
1708 }
1709 elsif (! exists $utf8::loose_to_file_of{$loose}) {
1710
1711 # loose_to_file_of is a complete list of loose names. If not
1712 # there, the input is unknown.
1713 return;
1714 }
1715 else {
1716
1717 # Here we found the name but not its aliases, so it has to
1718 # exist. This means it must be one of the Perl single-form
1719 # extensions. First see if it is for a property-value
1720 # combination in one of the following properties.
1721 my @list;
1722 foreach my $property ("gc", "script") {
1723 @list = prop_value_aliases($property, $loose);
1724 last if @list;
1725 }
1726 if (@list) {
1727
1728 # Here, it is one of those property-value combination
1729 # single-form synonyms. There are ambiguities with some
1730 # of these. Check against the list for these, and adjust
1731 # if necessary.
1732 for my $i (0 .. @list -1) {
1733 if (exists $ambiguous_names
1734 {utf8::_loose_name(lc $list[$i])})
1735 {
1736 # The ambiguity is resolved by toggling whether or
1737 # not it has an 'is' prefix
1738 $list[$i] =~ s/^Is_// or $list[$i] =~ s/^/Is_/;
1739 }
1740 }
1741 return @list;
1742 }
1743
1744 # Here, it wasn't one of the gc or script single-form
1745 # extensions. It could be a block property single-form
1746 # extension. An 'in' prefix definitely means that, and should
2a4f2769
KW
1747 # be looked up without the prefix. However, starting in
1748 # Unicode 6.1, we have to special case 'indic...', as there
1749 # is a property that begins with that name. We shouldn't
1750 # strip the 'in' from that. I'm (khw) generalizing this to
1751 # 'indic' instead of the single property, because I suspect
1752 # that others of this class may come along in the future.
1753 # However, this could backfire and a block created whose name
1754 # begins with 'dic...', and we would want to strip the 'in'.
1755 # At which point this would have to be tweaked.
1756 my $began_with_in = $loose =~ s/^in(?!dic)//;
7ef25837
KW
1757 @list = prop_value_aliases("block", $loose);
1758 if (@list) {
1759 map { $_ =~ s/^/In_/ } @list;
1760 return @list;
1761 }
1762
1763 # Here still haven't found it. The last opportunity for it
1764 # being valid is only if it began with 'is'. We retry without
1765 # the 'is', setting a flag to that effect so that we don't
1766 # accept things that begin with 'isis...'
1767 if (! $retrying && ! $began_with_in && $loose =~ s/^is//) {
1768 $retrying = 1;
1769 goto RETRY;
1770 }
1771
1772 # Here, didn't find it. Since it was in %loose_to_file_of, we
1773 # should have been able to find it.
1774 carp __PACKAGE__, "::prop_aliases: Unexpectedly could not find '$prop'. Send bug report to perlbug\@perl.org";
1775 return;
1776 }
1777 }
1778 }
1779
1780 if (! $list_ref) {
1781 # Here, we have set $prop to a standard form name of the input. Look
1782 # it up in the structure created by mktables for this purpose, which
1783 # contains both strict and loosely matched properties. Avoid
1784 # autovivifying.
1785 $list_ref = $prop_aliases{$prop} if exists $prop_aliases{$prop};
1786 return unless $list_ref;
1787 }
1788
1789 # The full name is in element 1.
1790 return $list_ref->[1] unless wantarray;
1791
cb3150f5 1792 return @{_dclone $list_ref};
7ef25837
KW
1793}
1794
1795=pod
1796
1797=head2 B<prop_value_aliases()>
1798
1799 use Unicode::UCD 'prop_value_aliases';
1800
1801 my ($short_name, $full_name, @other_names)
1802 = prop_value_aliases("Gc", "Punct");
1803 my $same_full_name = prop_value_aliases("Gc", "P"); # Scalar cntxt
1804 my ($same_short_name) = prop_value_aliases("Gc", "P"); # gets 0th
1805 # element
1806 print "The full name is $full_name\n";
1807 print "The short name is $short_name\n";
1808 print "The other aliases are: ", join(", ", @other_names), "\n";
1809
1810 prints:
1811 The full name is Punctuation
1812 The short name is P
1813 The other aliases are: Punct
1814
1815Some Unicode properties have a restricted set of legal values. For example,
1816all binary properties are restricted to just C<true> or C<false>; and there
1817are only a few dozen possible General Categories.
1818
1819For such properties, there are usually several synonyms for each possible
1820value. For example, in binary properties, I<truth> can be represented by any of
1821the strings "Y", "Yes", "T", or "True"; and the General Category
1822"Punctuation" by that string, or "Punct", or simply "P".
1823
1824Like property names, there is typically at least a short name for each such
1825property-value, and a long name. If you know any name of the property-value,
1826you can use C<prop_value_aliases>() to get the long name (when called in
1827scalar context), or a list of all the names, with the short name in the 0th
1828element, the long name in the next element, and any other synonyms in the
1829remaining elements, in no particular order, except that any all-numeric
1830synonyms will be last.
1831
1832The long name is returned in a form nicely capitalized, suitable for printing.
1833
1834Case, white space, hyphens, and underscores are ignored in the input parameters
1835(except for the trailing underscore in the old-form grandfathered-in general
1836category property value C<"L_">, which is better written as C<"LC">).
1837
1838If either name is unknown, C<undef> is returned. Note that Perl typically
1839recognizes property names in regular expressions with an optional C<"Is_>"
1840(with or without the underscore) prefixed to them, such as C<\p{isgc=punct}>.
1841This function does not recognize those in the property parameter, returning
1842C<undef>.
1843
1844If called with a property that doesn't have synonyms for its values, it
1845returns the input value, possibly normalized with capitalization and
1846underscores.
1847
1848For the block property, new-style block names are returned (see
1849L</Old-style versus new-style block names>).
1850
1851To find the synonyms for single-forms, such as C<\p{Any}>, use
1852L</prop_aliases()> instead.
1853
1854C<prop_value_aliases> does not know about any user-defined properties, and
1855will return C<undef> if called with one of those.
1856
1857=cut
1858
1859# These are created by mktables for this routine and stored in unicore/UCD.pl
1860# where their structures are described.
1861our %loose_to_standard_value;
1862our %prop_value_aliases;
1863
1864sub prop_value_aliases ($$) {
1865 my ($prop, $value) = @_;
1866 return unless defined $prop && defined $value;
1867
1868 require "unicore/UCD.pl";
1869 require "utf8_heavy.pl";
1870
1871 # Find the property name synonym that's used as the key in other hashes,
1872 # which is element 0 in the returned list.
1873 ($prop) = prop_aliases($prop);
1874 return if ! $prop;
1875 $prop = utf8::_loose_name(lc $prop);
1876
1877 # Here is a legal property, but the hash below (created by mktables for
1878 # this purpose) only knows about the properties that have a very finite
1879 # number of potential values, that is not ones whose value could be
1880 # anything, like most (if not all) string properties. These don't have
1881 # synonyms anyway. Simply return the input. For example, there is no
1882 # synonym for ('Uppercase_Mapping', A').
1883 return $value if ! exists $prop_value_aliases{$prop};
1884
1885 # The value name may be loosely or strictly matched; we don't know yet.
1886 # But both types use lower-case.
1887 $value = lc $value;
1888
1889 # If the name isn't found under loose matching, it certainly won't be
1890 # found under strict
1891 my $loose_value = utf8::_loose_name($value);
1892 return unless exists $loose_to_standard_value{"$prop=$loose_value"};
1893
1894 # Similarly if the combination under loose matching doesn't exist, it
1895 # won't exist under strict.
1896 my $standard_value = $loose_to_standard_value{"$prop=$loose_value"};
1897 return unless exists $prop_value_aliases{$prop}{$standard_value};
1898
1899 # Here we did find a combination under loose matching rules. But it could
1900 # be that is a strict property match that shouldn't have matched.
1901 # %prop_value_aliases is set up so that the strict matches will appear as
1902 # if they were in loose form. Thus, if the non-loose version is legal,
1903 # we're ok, can skip the further check.
1904 if (! exists $utf8::stricter_to_file_of{"$prop=$value"}
1905
1906 # We're also ok and skip the further check if value loosely matches.
1907 # mktables has verified that no strict name under loose rules maps to
1908 # an existing loose name. This code relies on the very limited
1909 # circumstances that strict names can be here. Strict name matching
1910 # happens under two conditions:
1911 # 1) when the name begins with an underscore. But this function
1912 # doesn't accept those, and %prop_value_aliases doesn't have
1913 # them.
1914 # 2) When the values are numeric, in which case we need to look
1915 # further, but their squeezed-out loose values will be in
1916 # %stricter_to_file_of
1917 && exists $utf8::stricter_to_file_of{"$prop=$loose_value"})
1918 {
1919 # The only thing that's legal loosely under strict is that can have an
1920 # underscore between digit pairs XXX
1921 while ($value =~ s/(\d)_(\d)/$1$2/g) {}
1922 return unless exists $utf8::stricter_to_file_of{"$prop=$value"};
1923 }
1924
1925 # Here, we know that the combination exists. Return it.
1926 my $list_ref = $prop_value_aliases{$prop}{$standard_value};
1927 if (@$list_ref > 1) {
1928 # The full name is in element 1.
1929 return $list_ref->[1] unless wantarray;
1930
cb3150f5 1931 return @{_dclone $list_ref};
7ef25837
KW
1932 }
1933
1934 return $list_ref->[0] unless wantarray;
1935
1936 # Only 1 element means that it repeats
1937 return ( $list_ref->[0], $list_ref->[0] );
1938}
7319f91d 1939
681d705c
KW
1940# All 1 bits is the largest possible UV.
1941$Unicode::UCD::MAX_CP = ~0;
1942
1943=pod
1944
1945=head2 B<prop_invlist()>
1946
1947C<prop_invlist> returns an inversion list (described below) that defines all the
1948code points for the binary Unicode property (or "property=value" pair) given
1949by the input parameter string:
1950
1951 use feature 'say';
1952 use Unicode::UCD 'prop_invlist';
1953 say join ", ", prop_invlist("Any");
1954
1955 prints:
1956 0, 1114112
1957
1958An empty list is returned if the input is unknown; the number of elements in
1959the list is returned if called in scalar context.
1960
1961L<perluniprops|perluniprops/Properties accessible through \p{} and \P{}> gives
1962the list of properties that this function accepts, as well as all the possible
1963forms for them (including with the optional "Is_" prefixes). (Except this
1964function doesn't accept any Perl-internal properties, some of which are listed
1965there.) This function uses the same loose or tighter matching rules for
1966resolving the input property's name as is done for regular expressions. These
1967are also specified in L<perluniprops|perluniprops/Properties accessible
1968through \p{} and \P{}>. Examples of using the "property=value" form are:
1969
1970 say join ", ", prop_invlist("Script=Shavian");
1971
1972 prints:
1973 66640, 66688
1974
1975 say join ", ", prop_invlist("ASCII_Hex_Digit=No");
1976
1977 prints:
1978 0, 48, 58, 65, 71, 97, 103
1979
1980 say join ", ", prop_invlist("ASCII_Hex_Digit=Yes");
1981
1982 prints:
1983 48, 58, 65, 71, 97, 103
1984
1985Inversion lists are a compact way of specifying Unicode property-value
1986definitions. The 0th item in the list is the lowest code point that has the
1987property-value. The next item (item [1]) is the lowest code point beyond that
1988one that does NOT have the property-value. And the next item beyond that
1989([2]) is the lowest code point beyond that one that does have the
1990property-value, and so on. Put another way, each element in the list gives
1991the beginning of a range that has the property-value (for even numbered
1992elements), or doesn't have the property-value (for odd numbered elements).
1993The name for this data structure stems from the fact that each element in the
1994list toggles (or inverts) whether the corresponding range is or isn't on the
1995list.
1996
1997In the final example above, the first ASCII Hex digit is code point 48, the
1998character "0", and all code points from it through 57 (a "9") are ASCII hex
1999digits. Code points 58 through 64 aren't, but 65 (an "A") through 70 (an "F")
2000are, as are 97 ("a") through 102 ("f"). 103 starts a range of code points
2001that aren't ASCII hex digits. That range extends to infinity, which on your
2002computer can be found in the variable C<$Unicode::UCD::MAX_CP>. (This
2003variable is as close to infinity as Perl can get on your platform, and may be
2004too high for some operations to work; you may wish to use a smaller number for
2005your purposes.)
2006
2007Note that the inversion lists returned by this function can possibly include
2008non-Unicode code points, that is anything above 0x10FFFF. This is in
2009contrast to Perl regular expression matches on those code points, in which a
2010non-Unicode code point always fails to match. For example, both of these have
2011the same result:
2012
2013 chr(0x110000) =~ \p{ASCII_Hex_Digit=True} # Fails.
2014 chr(0x110000) =~ \p{ASCII_Hex_Digit=False} # Fails!
2015
2016And both raise a warning that a Unicode property is being used on a
2017non-Unicode code point. It is arguable as to which is the correct thing to do
2018here. This function has chosen the way opposite to the Perl regular
2019expression behavior. This allows you to easily flip to to the Perl regular
2020expression way (for you to go in the other direction would be far harder).
2021Simply add 0x110000 at the end of the non-empty returned list if it isn't
2022already that value; and pop that value if it is; like:
2023
2024 my @list = prop_invlist("foo");
2025 if (@list) {
2026 if ($list[-1] == 0x110000) {
2027 pop @list; # Defeat the turning on for above Unicode
2028 }
2029 else {
2030 push @list, 0x110000; # Turn off for above Unicode
2031 }
2032 }
2033
2034It is a simple matter to expand out an inversion list to a full list of all
2035code points that have the property-value:
2036
2037 my @invlist = prop_invlist($property_name);
2038 die "empty" unless @invlist;
2039 my @full_list;
2040 for (my $i = 0; $i < @invlist; $i += 2) {
2041 my $upper = ($i + 1) < @invlist
2042 ? $invlist[$i+1] - 1 # In range
2043 : $Unicode::UCD::MAX_CP; # To infinity. You may want
2044 # to stop much much earlier;
2045 # going this high may expose
2046 # perl deficiencies with very
2047 # large numbers.
2048 for my $j ($invlist[$i] .. $upper) {
2049 push @full_list, $j;
2050 }
2051 }
2052
2053C<prop_invlist> does not know about any user-defined nor Perl internal-only
2054properties, and will return C<undef> if called with one of those.
2055
2056=cut
2057
2058# User-defined properties could be handled with some changes to utf8_heavy.pl;
2059# and implementing here of dealing with EXTRAS. If done, consideration should
2060# be given to the fact that the user subroutine could return different results
2061# with each call; security issues need to be thought about.
2062
2063# These are created by mktables for this routine and stored in unicore/UCD.pl
2064# where their structures are described.
2065our %loose_defaults;
2066our $MAX_UNICODE_CODEPOINT;
2067
2068sub prop_invlist ($) {
2069 my $prop = $_[0];
2070 return if ! defined $prop;
2071
2072 require "utf8_heavy.pl";
2073
2074 # Warnings for these are only for regexes, so not applicable to us
2075 no warnings 'deprecated';
2076
2077 # Get the swash definition of the property-value.
2078 my $swash = utf8::SWASHNEW(__PACKAGE__, $prop, undef, 1, 0);
2079
2080 # Fail if not found, or isn't a boolean property-value, or is a
2081 # user-defined property, or is internal-only.
2082 return if ! $swash
2083 || ref $swash eq ""
2084 || $swash->{'BITS'} != 1
2085 || $swash->{'USER_DEFINED'}
2086 || $prop =~ /^\s*_/;
2087
2088 if ($swash->{'EXTRAS'}) {
2089 carp __PACKAGE__, "::prop_invlist: swash returned for $prop unexpectedly has EXTRAS magic";
2090 return;
2091 }
2092 if ($swash->{'SPECIALS'}) {
2093 carp __PACKAGE__, "::prop_invlist: swash returned for $prop unexpectedly has SPECIALS magic";
2094 return;
2095 }
2096
2097 my @invlist;
2098
2099 # The input lines look like:
2100 # 0041\t005A # [26]
2101 # 005F
2102
2103 # Split into lines, stripped of trailing comments
2104 foreach my $range (split "\n",
2105 $swash->{'LIST'} =~ s/ \s* (?: \# .* )? $ //xmgr)
2106 {
2107 # And find the beginning and end of the range on the line
2108 my ($hex_begin, $hex_end) = split "\t", $range;
2109 my $begin = hex $hex_begin;
2110
a39cc031
KW
2111 # If the new range merely extends the old, we remove the marker
2112 # created the last time through the loop for the old's end, which
2113 # causes the new one's end to be used instead.
2114 if (@invlist && $begin == $invlist[-1]) {
2115 pop @invlist;
2116 }
2117 else {
2f3f243e
KW
2118 # Add the beginning of the range
2119 push @invlist, $begin;
a39cc031 2120 }
681d705c
KW
2121
2122 if (defined $hex_end) { # The next item starts with the code point 1
2123 # beyond the end of the range.
2124 push @invlist, hex($hex_end) + 1;
2125 }
2126 else { # No end of range, is a single code point.
2127 push @invlist, $begin + 1;
2128 }
2129 }
2130
2131 require "unicore/UCD.pl";
2132 my $FIRST_NON_UNICODE = $MAX_UNICODE_CODEPOINT + 1;
2133
2134 # Could need to be inverted: add or subtract a 0 at the beginning of the
2135 # list. And to keep it from matching non-Unicode, add or subtract the
2136 # first non-unicode code point.
2137 if ($swash->{'INVERT_IT'}) {
2138 if (@invlist && $invlist[0] == 0) {
2139 shift @invlist;
2140 }
2141 else {
2142 unshift @invlist, 0;
2143 }
2144 if (@invlist && $invlist[-1] == $FIRST_NON_UNICODE) {
2145 pop @invlist;
2146 }
2147 else {
2148 push @invlist, $FIRST_NON_UNICODE;
2149 }
2150 }
2151
2152 # Here, the list is set up to include only Unicode code points. But, if
2153 # the table is the default one for the property, it should contain all
2154 # non-Unicode code points. First calculate the loose name for the
2155 # property. This is done even for strict-name properties, as the data
2156 # structure that mktables generates for us is set up so that we don't have
2157 # to worry about that. The property-value needs to be split if compound,
2158 # as the loose rules need to be independently calculated on each part. We
2159 # know that it is syntactically valid, or SWASHNEW would have failed.
2160
2161 $prop = lc $prop;
2162 my ($prop_only, $table) = split /\s*[:=]\s*/, $prop;
2163 if ($table) {
2164
2165 # May have optional prefixed 'is'
2166 $prop = utf8::_loose_name($prop_only) =~ s/^is//r;
2167 $prop = $utf8::loose_property_name_of{$prop};
2168 $prop .= "=" . utf8::_loose_name($table);
2169 }
2170 else {
2171 $prop = utf8::_loose_name($prop);
2172 }
2173 if (exists $loose_defaults{$prop}) {
2174
2175 # Here, is the default table. If a range ended with 10ffff, instead
2176 # continue that range to infinity, by popping the 110000; otherwise,
2177 # add the range from 11000 to infinity
2178 if (! @invlist || $invlist[-1] != $FIRST_NON_UNICODE) {
2179 push @invlist, $FIRST_NON_UNICODE;
2180 }
2181 else {
2182 pop @invlist;
2183 }
2184 }
2185
2186 return @invlist;
2187}
7319f91d 2188
62b3b855
KW
2189sub _search_invlist {
2190 # Find the range in the inversion list which contains a code point; that
2191 # is, find i such that l[i] <= code_point < l[i+1]
2192
2193 # If this is ever made public, could use to speed up .t specials. Would
2194 # need to use code point argument, as in other functions in this pm
2195
2196 my $list_ref = shift;
2197 my $code_point = shift;
2198 # Verify non-neg numeric XXX
2199
2200 my $max_element = @$list_ref - 1;
2201 return if ! $max_element < 0; # Undef if list is empty.
2202
2203 # Short cut something at the far-end of the table. This also allows us to
2204 # refer to element [$i+1] without fear of being out-of-bounds in the loop
2205 # below.
2206 return $max_element if $code_point >= $list_ref->[$max_element];
2207
2208 use integer; # want integer division
2209
2210 my $i = $max_element / 2;
2211
2212 my $lower = 0;
2213 my $upper = $max_element;
2214 while (1) {
2215
2216 if ($code_point >= $list_ref->[$i]) {
2217
2218 # Here we have met the lower constraint. We can quit if we
2219 # also meet the upper one.
2220 last if $code_point < $list_ref->[$i+1];
2221
2222 $lower = $i; # Still too low.
2223
2224 }
2225 else {
2226
2227 # Here, $code_point < $list_ref[$i], so look lower down.
2228 $upper = $i;
2229 }
2230
2231 # Split search domain in half to try again.
2232 my $temp = ($upper + $lower) / 2;
2233
2234 # No point in continuing unless $i changes for next time
2235 # in the loop.
2236 return $i if $temp == $i;
2237 $i = $temp;
2238 } # End of while loop
2239
2240 # Here we have found the offset
2241 return $i;
2242}
2243
2244=pod
2245
2246=head2 B<prop_invmap()>
2247
2248 use Unicode::UCD 'prop_invmap';
2249 my ($list_ref, $map_ref, $format, $missing)
2250 = prop_invmap("General Category");
2251
2252C<prop_invmap> is used to get the complete mapping definition for a property,
2253in the form of an inversion map. An inversion map consists of two parallel
2254arrays. One is an ordered list of code points that mark range beginnings, and
2255the other gives the value (or mapping) that all code points in the
2256corresponding range have.
2257
2258C<prop_invmap> is called with the name of the desired property. The name is
2259loosely matched, meaning that differences in case, white-space, hyphens, and
2260underscores are not meaningful (except for the trailing underscore in the
2261old-form grandfathered-in property C<"L_">, which is better written as C<"LC">,
2262or even better, C<"Gc=LC">).
2263
2264Many Unicode properties have more than one name (or alias). C<prop_invmap>
2265understands all of these, including Perl extensions to them. Ambiguities are
2266resolved as described above for L</prop_aliases()>. The Perl internal
2267property "Perl_Decimal_Digit, described below, is also accepted. C<undef> is
2268returned if the property name is unknown.
ee94c7d1
KW
2269See L<perluniprops/Properties accessible through Unicode::UCD> for the
2270properties acceptable as inputs to this function.
62b3b855
KW
2271
2272It is a fatal error to call this function except in list context.
2273
2274In addition to the the two arrays that form the inversion map, C<prop_invmap>
2275returns two other values; one is a scalar that gives some details as to the
2276format of the entries of the map array; the other is used for specialized
2277purposes, described at the end of this section.
2278
2279This means that C<prop_invmap> returns a 4 element list. For example,
2280
2281 my ($blocks_ranges_ref, $blocks_maps_ref, $format, $default)
2282 = prop_invmap("Block");
2283
2284In this call, the two arrays will be populated as shown below (for Unicode
22856.0):
2286
2287 Index @blocks_ranges @blocks_maps
2288 0 0x0000 Basic Latin
2289 1 0x0080 Latin-1 Supplement
2290 2 0x0100 Latin Extended-A
2291 3 0x0180 Latin Extended-B
2292 4 0x0250 IPA Extensions
2293 5 0x02B0 Spacing Modifier Letters
2294 6 0x0300 Combining Diacritical Marks
2295 7 0x0370 Greek and Coptic
2296 8 0x0400 Cyrillic
2297 ...
2298 233 0x2B820 No_Block
2299 234 0x2F800 CJK Compatibility Ideographs Supplement
2300 235 0x2FA20 No_Block
2301 236 0xE0000 Tags
2302 237 0xE0080 No_Block
2303 238 0xE0100 Variation Selectors Supplement
2304 239 0xE01F0 No_Block
2305 240 0xF0000 Supplementary Private Use Area-A
2306 241 0x100000 Supplementary Private Use Area-B
2307 242 0x110000 No_Block
2308
2309The first line (with Index [0]) means that the value for code point 0 is "Basic
2310Latin". The entry "0x0080" in the @blocks_ranges column in the second line
2311means that the value from the first line, "Basic Latin", extends to all code
2312points in the range from 0 up to but not including 0x0080, that is, through
647396da 2313127. In other words, the code points from 0 to 127 are all in the "Basic
62b3b855
KW
2314Latin" block. Similarly, all code points in the range from 0x0080 up to (but
2315not including) 0x0100 are in the block named "Latin-1 Supplement", etc.
2316(Notice that the return is the old-style block names; see L</Old-style versus
2317new-style block names>).
2318
2319The final line (with Index [242]) means that the value for all code points above
2320the legal Unicode maximum code point have the value "No_Block", which is the
2321term Unicode uses for a non-existing block.
2322
2323The arrays completely specify the mappings for all possible code points.
2324The final element in an inversion map returned by this function will always be
2325for the range that consists of all the code points that aren't legal Unicode,
2326but that are expressible on the platform. (That is, it starts with code point
23270x110000, the first code point above the legal Unicode maximum, and extends to
2328infinity.) The value for that range will be the same that any typical
2329unassigned code point has for the specified property. (Certain unassigned
2330code points are not "typical"; for example the non-character code points, or
2331those in blocks that are to be written right-to-left. The above-Unicode
2332range's value is not based on these atypical code points.) It could be argued
2333that, instead of treating these as unassigned Unicode code points, the value
2334for this range should be C<undef>. If you wish, you can change the returned
2335arrays accordingly.
2336
2337The maps are almost always simple scalars that should be interpreted as-is.
2338These values are those given in the Unicode-supplied data files, which may be
2339inconsistent as to capitalization and as to which synonym for a property-value
2340is given. The results may be normalized by using the L</prop_value_aliases()>
2341function.
2342
2343There are exceptions to the simple scalar maps. Some properties have some
2344elements in their map list that are themselves lists of scalars; and some
2345special strings are returned that are not to be interpreted as-is. Element
2346[2] (placed into C<$format> in the example above) of the returned four element
647396da 2347list tells you if the map has any of these special elements or not, as follows:
62b3b855
KW
2348
2349=over
2350
dc8d8ea6 2351=item B<C<s>>
62b3b855
KW
2352
2353means all the elements of the map array are simple scalars, with no special
2354elements. Almost all properties are like this, like the C<block> example
2355above.
2356
dc8d8ea6 2357=item B<C<sl>>
62b3b855 2358
647396da 2359means that some of the map array elements have the form given by C<"s">, and
62b3b855
KW
2360the rest are lists of scalars. For example, here is a portion of the output
2361of calling C<prop_invmap>() with the "Script Extensions" property:
2362
2363 @scripts_ranges @scripts_maps
2364 ...
c2ca0207
KW
2365 0x0953 Devanagari
2366 0x0964 [ Bengali, Devanagari, Gurumukhi, Oriya ]
2367 0x0966 Devanagari
62b3b855
KW
2368 0x0970 Common
2369
647396da
KW
2370Here, the code points 0x964 and 0x965 are both used in Bengali,
2371Devanagari, Gurmukhi, and Oriya, but no other scripts.
62b3b855 2372
647396da 2373The Name_Alias property is also of this form. But each scalar consists of two
58b75e36 2374components: 1) the name, and 2) the type of alias this is. They are
7620cb10
KW
2375separated by a colon and a space. In Unicode 6.1, there are several alias types:
2376
2377=over
2378
2379=item C<correction>
2380
2381indicates that the name is a corrected form for the
2382original name (which remains valid) for the same code point.
2383
2384=item C<control>
2385
2386adds a new name for a control character.
2387
2388=item C<alternate>
2389
2390is an alternate name for a character
2391
2392=item C<figment>
2393
2394is a name for a character that has been documented but was never in any
2395actual standard.
2396
2397=item C<abbreviation>
2398
2399is a common abbreviation for a character
2400
2401=back
2402
2403The lists are ordered (roughly) so the most preferred names come before less
2404preferred ones.
58b75e36
KW
2405
2406For example,
2407
7620cb10
KW
2408 @aliases_ranges @alias_maps
2409 ...
2410 0x009E [ 'PRIVACY MESSAGE: control', 'PM: abbreviation' ]
2411 0x009F [ 'APPLICATION PROGRAM COMMAND: control',
2412 'APC: abbreviation'
2413 ]
2414 0x00A0 'NBSP: abbreviation'
2415 0x00A1 ""
2416 0x00AD 'SHY: abbreviation'
2417 0x00AE ""
2418 0x01A2 'LATIN CAPITAL LETTER GHA: correction'
2419 0x01A3 'LATIN SMALL LETTER GHA: correction'
2420 0x01A4 ""
58b75e36 2421 ...
58b75e36 2422
7620cb10
KW
2423A map to the empty string means that there is no alias defined for the code
2424point.
58b75e36 2425
d11155ec 2426=item B<C<a>>
62b3b855 2427
647396da 2428is like C<"s"> in that all the map array elements are scalars, but here they are
d11155ec
KW
2429restricted to all being integers, and some have to be adjusted (hence the name
2430C<"a">) to get the correct result. For example, in:
62b3b855
KW
2431
2432 my ($uppers_ranges_ref, $uppers_maps_ref, $format)
2433 = prop_invmap("Simple_Uppercase_Mapping");
2434
2435the returned arrays look like this:
2436
2437 @$uppers_ranges_ref @$uppers_maps_ref Note
bf7fe2df 2438 0 0
d11155ec 2439 97 65 'a' maps to 'A', b => B ...
bf7fe2df 2440 123 0
d11155ec 2441 181 924 MICRO SIGN => Greek Cap MU
bf7fe2df 2442 182 0
62b3b855
KW
2443 ...
2444
d11155ec
KW
2445Let's start with the second line. It says that the uppercase of code point 97
2446is 65; or C<uc("a")> == "A". But the line is for the entire range of code
2447points 97 through 122. To get the mapping for any code point in a range, you
2448take the offset it has from the beginning code point of the range, and add
2449that to the mapping for that first code point. So, the mapping for 122 ("z")
2450is derived by taking the offset of 122 from 97 (=25) and adding that to 65,
2451yielding 90 ("z"). Likewise for everything in between.
2452
2453The first line works the same way. The first map in a range is always the
2454correct value for its code point (because the adjustment is 0). Thus the
2455C<uc(chr(0))> is just itself. Also, C<uc(chr(1))> is also itself, as the
2456adjustment is 0+1-0 .. C<uc(chr(96))> is 96.
bf7fe2df 2457
d11155ec
KW
2458Requiring this simple adjustment allows the returned arrays to be
2459significantly smaller than otherwise, up to a factor of 10, speeding up
2460searching through them.
62b3b855 2461
d11155ec 2462=item B<C<al>>
62b3b855 2463
d11155ec 2464means that some of the map array elements have the form given by C<"a">, and
62b3b855
KW
2465the rest are ordered lists of code points.
2466For example, in:
2467
2468 my ($uppers_ranges_ref, $uppers_maps_ref, $format)
2469 = prop_invmap("Uppercase_Mapping");
2470
2471the returned arrays look like this:
2472
2473 @$uppers_ranges_ref @$uppers_maps_ref
bf7fe2df 2474 0 0
d11155ec 2475 97 65
bf7fe2df 2476 123 0
d11155ec 2477 181 924
bf7fe2df 2478 182 0
62b3b855
KW
2479 ...
2480 0x0149 [ 0x02BC 0x004E ]
bf7fe2df 2481 0x014A 0
d11155ec 2482 0x014B 330
62b3b855
KW
2483 ...
2484
2485This is the full Uppercase_Mapping property (as opposed to the
d11155ec 2486Simple_Uppercase_Mapping given in the example for format C<"a">). The only
62b3b855
KW
2487difference between the two in the ranges shown is that the code point at
24880x0149 (LATIN SMALL LETTER N PRECEDED BY APOSTROPHE) maps to a string of two
2489characters, 0x02BC (MODIFIER LETTER APOSTROPHE) followed by 0x004E (LATIN
2490CAPITAL LETTER N).
2491
d11155ec
KW
2492No adjustments are needed to entries that are references to arrays; each such
2493entry will have exactly one element in its range, so the offset is always 0.
bf7fe2df 2494
d11155ec 2495=item B<C<ae>>
b0b13ada 2496
d11155ec
KW
2497This is like C<"a">, but some elements are the empty string, and should not be
2498adjusted.
b0b13ada
KW
2499The one internal Perl property accessible by C<prop_invmap> is of this type:
2500"Perl_Decimal_Digit" returns an inversion map which gives the numeric values
2501that are represented by the Unicode decimal digit characters. Characters that
2502don't represent decimal digits map to the empty string, like so:
2503
2504 @digits @values
2505 0x0000 ""
d11155ec 2506 0x0030 0
b0b13ada 2507 0x003A: ""
d11155ec 2508 0x0660: 0
b0b13ada 2509 0x066A: ""
d11155ec 2510 0x06F0: 0
b0b13ada 2511 0x06FA: ""
d11155ec 2512 0x07C0: 0
b0b13ada 2513 0x07CA: ""
d11155ec 2514 0x0966: 0
b0b13ada
KW
2515 ...
2516
2517This means that the code points from 0 to 0x2F do not represent decimal digits;
d11155ec
KW
2518the code point 0x30 (DIGIT ZERO) represents 0; code point 0x31, (DIGIT ONE),
2519represents 0+1-0 = 1; ... code point 0x39, (DIGIT NINE), represents 0+9-0 = 9;
2520... code points 0x3A through 0x65F do not represent decimal digits; 0x660
2521(ARABIC-INDIC DIGIT ZERO), represents 0; ... 0x07C1 (NKO DIGIT ONE),
2522represents 0+1-0 = 1 ...
b0b13ada 2523
d11155ec 2524=item B<C<ale>>
62b3b855 2525
d11155ec
KW
2526is a combination of the C<"al"> type and the C<"ae"> type. Some of
2527the map array elements have the forms given by C<"al">, and
62b3b855
KW
2528the rest are the empty string. The property C<NFKC_Casefold> has this form.
2529An example slice is:
2530
2531 @$ranges_ref @$maps_ref Note
2532 ...
d11155ec
KW
2533 0x00AA 97 FEMININE ORDINAL INDICATOR => 'a'
2534 0x00AB 0
62b3b855 2535 0x00AD SOFT HYPHEN => ""
d11155ec 2536 0x00AE 0
62b3b855 2537 0x00AF [ 0x0020, 0x0304 ] MACRON => SPACE . COMBINING MACRON
d11155ec 2538 0x00B0 0
62b3b855
KW
2539 ...
2540
4f143a72 2541=item B<C<ar>>
6cc45523
KW
2542
2543means that all the elements of the map array are either rational numbers or
2544the string C<"NaN">, meaning "Not a Number". A rational number is either an
2545integer, or two integers separated by a solidus (C<"/">). The second integer
2546represents the denominator of the division implied by the solidus, and is
6329003c
KW
2547actually always positive, so it is guaranteed not to be 0 and to not to be
2548signed. When the element is a plain integer (without the
4f143a72
KW
2549solidus), it may need to be adjusted to get the correct value by adding the
2550offset, just as other C<"a"> properties. No adjustment is needed for
2551fractions, as the range is guaranteed to have just a single element, and so
2552the offset is always 0.
2553
2554If you want to convert the returned map to entirely scalar numbers, you
6cc45523
KW
2555can use something like this:
2556
2557 my ($invlist_ref, $invmap_ref, $format) = prop_invmap($property);
4f143a72 2558 if ($format && $format eq "ar") {
6cc45523
KW
2559 map { $_ = eval $_ } @$invmap_ref;
2560 }
2561
2562Here's some entries from the output of the property "Nv", which has format
4f143a72 2563C<"ar">.
6cc45523 2564
4f143a72 2565 @numerics_ranges @numerics_maps Note
6cc45523 2566 0x00 "NaN"
4f143a72 2567 0x30 0 DIGIT 0 .. DIGIT 9
6cc45523 2568 0x3A "NaN"
4f143a72 2569 0xB2 2 SUPERSCRIPTs 2 and 3
6cc45523 2570 0xB4 "NaN"
4f143a72 2571 0xB9 1 SUPERSCRIPT 1
6cc45523 2572 0xBA "NaN"
4f143a72
KW
2573 0xBC 1/4 VULGAR FRACTION 1/4
2574 0xBD 1/2 VULGAR FRACTION 1/2
2575 0xBE 3/4 VULGAR FRACTION 3/4
6cc45523 2576 0xBF "NaN"
4f143a72
KW
2577 0x660 0 ARABIC-INDIC DIGIT ZERO .. NINE
2578 0x66A "NaN"
6cc45523 2579
dc8d8ea6 2580=item B<C<n>>
62b3b855
KW
2581
2582means the Name property. All the elements of the map array are simple
2583scalars, but some of them contain special strings that require more work to
2584get the actual name.
2585
2586Entries such as:
2587
2588 CJK UNIFIED IDEOGRAPH-<code point>
2589
2590mean that the name for the code point is "CJK UNIFIED IDEOGRAPH-"
2591with the code point (expressed in hexadecimal) appended to it, like "CJK
647396da
KW
2592UNIFIED IDEOGRAPH-3403" (similarly for S<C<CJK COMPATIBILITY IDEOGRAPH-E<lt>code
2593pointE<gt>>>).
62b3b855
KW
2594
2595Also, entries like
2596
2597 <hangul syllable>
2598
2599means that the name is algorithmically calculated. This is easily done by
2600the function L<charnames/charnames::viacode(code)>.
2601
2602Note that for control characters (C<Gc=cc>), Unicode's data files have the
2603string "C<E<lt>controlE<gt>>", but the real name of each of these characters is the empty
7620cb10 2604string. This function returns that real name, the empty string. (There are
647396da
KW
2605names for these characters, but they are considered aliases, not the Name
2606property name, and are contained in the C<Name_Alias> property.)
62b3b855 2607
d11155ec 2608=item B<C<ad>>
62b3b855 2609
d11155ec 2610means the Decomposition_Mapping property. This property is like C<"al">
bea2c146 2611properties, except that one of the scalar elements is of the form:
62b3b855
KW
2612
2613 <hangul syllable>
2614
bea2c146
KW
2615This signifies that this entry should be replaced by the decompositions for
2616all the code points whose decomposition is algorithmically calculated. (All
6329003c
KW
2617of them are currently in one range and no others outisde the range are likely
2618to ever be added to Unicode; the C<"n"> format
bea2c146 2619has this same entry.) These can be generated via the function
62b3b855
KW
2620L<Unicode::Normalize::NFD()|Unicode::Normalize>.
2621
62b3b855
KW
2622Note that the mapping is the one that is specified in the Unicode data files,
2623and to get the final decomposition, it may need to be applied recursively.
2624
2625=back
2626
d11155ec
KW
2627Note that a format begins with the letter "a" if and only the property it is
2628for requires adjustments by adding the offsets in multi-element ranges. For
2629all these properties, an entry should be adjusted only if the map is a scalar
2630which is an integer. That is, it must match the regular expression:
2631
2632 / ^ -? \d+ $ /xa
2633
2634Further, the first element in a range never needs adjustment, as the
2635adjustment would be just adding 0.
2636
62b3b855
KW
2637A binary search can be used to quickly find a code point in the inversion
2638list, and hence its corresponding mapping.
2639
2640The final element (index [3], assigned to C<$default> in the "block" example) in
2641the four element list returned by this function may be useful for applications
2642that wish to convert the returned inversion map data structure into some
2643other, such as a hash. It gives the mapping that most code points map to
2644under the property. If you establish the convention that any code point not
2645explicitly listed in your data structure maps to this value, you can
2646potentially make your data structure much smaller. As you construct your data
2647structure from the one returned by this function, simply ignore those ranges
2648that map to this value, generally called the "default" value. For example, to
2649convert to the data structure searchable by L</charinrange()>, you can follow
6329003c 2650this recipe for properties that don't require adjustments:
62b3b855
KW
2651
2652 my ($list_ref, $map_ref, $format, $missing) = prop_invmap($property);
2653 my @range_list;
6329003c
KW
2654
2655 # Look at each element in the list, but the -2 is needed because we
2656 # look at $i+1 in the loop, and the final element is guaranteed to map
2657 # to $missing by prop_invmap(), so we would skip it anyway.
62b3b855
KW
2658 for my $i (0 .. @$list_ref - 2) {
2659 next if $map_ref->[$i] eq $missing;
2660 push @range_list, [ $list_ref->[$i],
2661 $list_ref->[$i+1],
2662 $map_ref->[$i]
2663 ];
2664 }
2665
2666 print charinrange(\@range_list, $code_point), "\n";
2667
62b3b855
KW
2668With this, C<charinrange()> will return C<undef> if its input code point maps
2669to C<$missing>. You can avoid this by omitting the C<next> statement, and adding
2670a line after the loop to handle the final element of the inversion map.
2671
6329003c
KW
2672Similarly, this recipe can be used for properties that do require adjustments:
2673
2674 for my $i (0 .. @$list_ref - 2) {
2675 next if $map_ref->[$i] eq $missing;
2676
2677 # prop_invmap() guarantees that if the mapping is to an array, the
2678 # range has just one element, so no need to worry about adjustments.
2679 if (ref $map_ref->[$i]) {
2680 push @range_list,
2681 [ $list_ref->[$i], $list_ref->[$i], $map_ref->[$i] ];
2682 }
2683 else { # Otherwise each element is actually mapped to a separate
2684 # value, so the range has to be split into single code point
2685 # ranges.
2686
2687 my $adjustment = 0;
2688
2689 # For each code point that gets mapped to something...
2690 for my $j ($list_ref->[$i] .. $list_ref->[$i+1] -1 ) {
2691
2692 # ... add a range consisting of just it mapping to the
2693 # original plus the adjustment, which is incremented for the
2694 # next time through the loop, as the offset increases by 1
2695 # for each element in the range
2696 push @range_list,
2697 [ $j, $j, $map_ref->[$i] + $adjustment++ ];
2698 }
2699 }
2700 }
62b3b855
KW
2701
2702Note that the inversion maps returned for the C<Case_Folding> and
2703C<Simple_Case_Folding> properties do not include the Turkic-locale mappings.
2704Use L</casefold()> for these.
2705
62b3b855
KW
2706C<prop_invmap> does not know about any user-defined properties, and will
2707return C<undef> if called with one of those.
2708
2709=cut
2710
2711# User-defined properties could be handled with some changes to utf8_heavy.pl;
2712# if done, consideration should be given to the fact that the user subroutine
2713# could return different results with each call, which could lead to some
2714# security issues.
2715
2716# One could store things in memory so they don't have to be recalculated, but
2717# it is unlikely this will be called often, and some properties would take up
2718# significant memory.
2719
2720# These are created by mktables for this routine and stored in unicore/UCD.pl
2721# where their structures are described.
2722our @algorithmic_named_code_points;
2723our $HANGUL_BEGIN;
2724our $HANGUL_COUNT;
2725
2726sub prop_invmap ($) {
2727
2728 croak __PACKAGE__, "::prop_invmap: must be called in list context" unless wantarray;
2729
2730 my $prop = $_[0];
2731 return unless defined $prop;
2732
2733 # Fail internal properties
2734 return if $prop =~ /^_/;
2735
2736 # The values returned by this function.
2737 my (@invlist, @invmap, $format, $missing);
2738
2739 # The swash has two components we look at, the base list, and a hash,
2740 # named 'SPECIALS', containing any additional members whose mappings don't
2741 # fit into the the base list scheme of things. These generally 'override'
2742 # any value in the base list for the same code point.
2743 my $overrides;
2744
2745 require "utf8_heavy.pl";
2746 require "unicore/UCD.pl";
2747
2748RETRY:
2749
647396da
KW
2750 # If there are multiple entries for a single code point
2751 my $has_multiples = 0;
2752
62b3b855
KW
2753 # Try to get the map swash for the property. They have 'To' prepended to
2754 # the property name, and 32 means we will accept 32 bit return values.
647396da 2755 # The 0 means we aren't calling this from tr///.
62b3b855
KW
2756 my $swash = utf8::SWASHNEW(__PACKAGE__, "To$prop", undef, 32, 0);
2757
2758 # If didn't find it, could be because needs a proxy. And if was the
2759 # 'Block' or 'Name' property, use a proxy even if did find it. Finding it
647396da
KW
2760 # in these cases would be the result of the installation changing mktables
2761 # to output the Block or Name tables. The Block table gives block names
2762 # in the new-style, and this routine is supposed to return old-style block
2763 # names. The Name table is valid, but we need to execute the special code
2764 # below to add in the algorithmic-defined name entries.
34132297 2765 # And NFKCCF needs conversion, so handle that here too.
62b3b855 2766 if (ref $swash eq ""
34132297 2767 || $swash->{'TYPE'} =~ / ^ To (?: Blk | Na | NFKCCF ) $ /x)
62b3b855
KW
2768 {
2769
2770 # Get the short name of the input property, in standard form
2771 my ($second_try) = prop_aliases($prop);
2772 return unless $second_try;
2773 $second_try = utf8::_loose_name(lc $second_try);
2774
2775 if ($second_try eq "in") {
2776
2777 # This property is identical to age for inversion map purposes
2778 $prop = "age";
2779 goto RETRY;
2780 }
cfc5eb77 2781 elsif ($second_try =~ / ^ s ( cf | fc | [ltu] c ) $ /x) {
62b3b855 2782
75e7c50b
KW
2783 # These properties use just the LIST part of the full mapping,
2784 # which includes the simple maps that are otherwise overridden by
2785 # the SPECIALS. So all we need do is to not look at the SPECIALS;
2786 # set $overrides to indicate that
62b3b855 2787 $overrides = -1;
62b3b855 2788
75e7c50b 2789 # The full name is the simple name stripped of its initial 's'
cfc5eb77
KW
2790 $prop = $1;
2791
2792 # .. except for this case
2793 $prop = 'cf' if $prop eq 'fc';
2794
62b3b855
KW
2795 goto RETRY;
2796 }
2797 elsif ($second_try eq "blk") {
2798
2799 # We use the old block names. Just create a fake swash from its
2800 # data.
2801 _charblocks();
2802 my %blocks;
2803 $blocks{'LIST'} = "";
2804 $blocks{'TYPE'} = "ToBlk";
2805 $utf8::SwashInfo{ToBlk}{'missing'} = "No_Block";
2806 $utf8::SwashInfo{ToBlk}{'format'} = "s";
2807
2808 foreach my $block (@BLOCKS) {
2809 $blocks{'LIST'} .= sprintf "%x\t%x\t%s\n",
2810 $block->[0],
2811 $block->[1],
2812 $block->[2];
2813 }
2814 $swash = \%blocks;
2815 }
2816 elsif ($second_try eq "na") {
2817
2818 # Use the combo file that has all the Name-type properties in it,
2819 # extracting just the ones that are for the actual 'Name'
2820 # property. And create a fake swash from it.
2821 my %names;
2822 $names{'LIST'} = "";
2823 my $original = do "unicore/Name.pl";
62b3b855
KW
2824 my $algorithm_names = \@algorithmic_named_code_points;
2825
3b6a8189
KW
2826 # We need to remove the names from it that are aliases. For that
2827 # we need to also read in that table. Create a hash with the keys
2828 # being the code points, and the values being a list of the
2829 # aliases for the code point key.
2830 my ($aliases_code_points, $aliases_maps, undef, undef) =
2831 &prop_invmap('Name_Alias');
2832 my %aliases;
2833 for (my $i = 0; $i < @$aliases_code_points; $i++) {
2834 my $code_point = $aliases_code_points->[$i];
2835 $aliases{$code_point} = $aliases_maps->[$i];
2836
2837 # If not already a list, make it into one, so that later we
2838 # can treat things uniformly
2839 if (! ref $aliases{$code_point}) {
2840 $aliases{$code_point} = [ $aliases{$code_point} ];
2841 }
2842
2843 # Remove the alias type from the entry, retaining just the
2844 # name.
2845 map { s/:.*// } @{$aliases{$code_point}};
2846 }
2847
62b3b855
KW
2848 my $i = 0;
2849 foreach my $line (split "\n", $original) {
2850 my ($hex_code_point, $name) = split "\t", $line;
2851
2852 # Weeds out all comments, blank lines, and named sequences
df46a385 2853 next if $hex_code_point =~ /[^[:xdigit:]]/a;
62b3b855
KW
2854
2855 my $code_point = hex $hex_code_point;
2856
2857 # The name of all controls is the default: the empty string.
2858 # The set of controls is immutable, so these hard-coded
2859 # constants work.
2860 next if $code_point <= 0x9F
2861 && ($code_point <= 0x1F || $code_point >= 0x7F);
2862
3b6a8189
KW
2863 # If this is a name_alias, it isn't a name
2864 next if grep { $_ eq $name } @{$aliases{$code_point}};
62b3b855
KW
2865
2866 # If we are beyond where one of the special lines needs to
2867 # be inserted ...
3b6a8189 2868 while ($i < @$algorithm_names
62b3b855
KW
2869 && $code_point > $algorithm_names->[$i]->{'low'})
2870 {
2871
2872 # ... then insert it, ahead of what we were about to
2873 # output
3b6a8189 2874 $names{'LIST'} .= sprintf "%x\t%x\t%s\n",
62b3b855
KW
2875 $algorithm_names->[$i]->{'low'},
2876 $algorithm_names->[$i]->{'high'},
2877 $algorithm_names->[$i]->{'name'};
2878
62b3b855
KW
2879 # Done with this range.
2880 $i++;
2881
3b6a8189
KW
2882 # We loop until all special lines that precede the next
2883 # regular one are output.
62b3b855
KW
2884 }
2885
3b6a8189
KW
2886 # Here, is a normal name.
2887 $names{'LIST'} .= sprintf "%x\t\t%s\n", $code_point, $name;
2888 } # End of loop through all the names
62b3b855
KW
2889
2890 $names{'TYPE'} = "ToNa";
2891 $utf8::SwashInfo{ToNa}{'missing'} = "";
2892 $utf8::SwashInfo{ToNa}{'format'} = "n";
2893 $swash = \%names;
2894 }
2895 elsif ($second_try =~ / ^ ( d [mt] ) $ /x) {
2896
2897 # The file is a combination of dt and dm properties. Create a
2898 # fake swash from the portion that we want.
2899 my $original = do "unicore/Decomposition.pl";
2900 my %decomps;
2901
2902 if ($second_try eq 'dt') {
2903 $decomps{'TYPE'} = "ToDt";
2904 $utf8::SwashInfo{'ToDt'}{'missing'} = "None";
2905 $utf8::SwashInfo{'ToDt'}{'format'} = "s";
d11155ec 2906 } # 'dm' is handled below, with 'nfkccf'
62b3b855
KW
2907
2908 $decomps{'LIST'} = "";
2909
2910 # This property has one special range not in the file: for the
1a4c9760
KW
2911 # hangul syllables. But not in Unicode version 1.
2912 UnicodeVersion() unless defined $v_unicode_version;
2913 my $done_hangul = ($v_unicode_version lt v2.0.0)
2914 ? 1
2915 : 0; # Have we done the hangul range ?
62b3b855
KW
2916 foreach my $line (split "\n", $original) {
2917 my ($hex_lower, $hex_upper, $type_and_map) = split "\t", $line;
2918 my $code_point = hex $hex_lower;
2919 my $value;
bea2c146 2920 my $redo = 0;
62b3b855
KW
2921
2922 # The type, enclosed in <...>, precedes the mapping separated
2923 # by blanks
2924 if ($type_and_map =~ / ^ < ( .* ) > \s+ (.*) $ /x) {
2925 $value = ($second_try eq 'dt') ? $1 : $2
2926 }
2927 else { # If there is no type specified, it's canonical
2928 $value = ($second_try eq 'dt')
2929 ? "Canonical" :
2930 $type_and_map;
2931 }
2932
2933 # Insert the hangul range at the appropriate spot.
2934 if (! $done_hangul && $code_point > $HANGUL_BEGIN) {
2935 $done_hangul = 1;
2936 $decomps{'LIST'} .=
2937 sprintf "%x\t%x\t%s\n",
2938 $HANGUL_BEGIN,
2939 $HANGUL_BEGIN + $HANGUL_COUNT - 1,
2940 ($second_try eq 'dt')
2941 ? "Canonical"
2942 : "<hangul syllable>";
2943 }
2944
1a4c9760
KW
2945 if ($value =~ / / && $hex_upper ne "" && $hex_upper ne $hex_lower) {
2946 $line = sprintf("%04X\t%s\t%s", hex($hex_lower) + 1, $hex_upper, $value);
2947 $hex_upper = "";
2948 $redo = 1;
2949 }
2950
62b3b855
KW
2951 # And append this to our constructed LIST.
2952 $decomps{'LIST'} .= "$hex_lower\t$hex_upper\t$value\n";
bea2c146
KW
2953
2954 redo if $redo;
62b3b855
KW
2955 }
2956 $swash = \%decomps;
2957 }
d11155ec
KW
2958 elsif ($second_try ne 'nfkccf') { # Don't know this property. Fail.
2959 return;
2960 }
2961
2962 if ($second_try eq 'nfkccf' || $second_try eq 'dm') {
34132297 2963
d11155ec
KW
2964 # The 'nfkccf' property is stored in the old format for backwards
2965 # compatibility for any applications that has read its file
2966 # directly before prop_invmap() existed.
2967 # And the code above has extracted the 'dm' property from its file
2968 # yielding the same format. So here we convert them to adjusted
2969 # format for compatibility with the other properties similar to
2970 # them.
2971 my %revised_swash;
34132297 2972
d11155ec 2973 # We construct a new converted list.
34132297 2974 my $list = "";
d11155ec
KW
2975
2976 my @ranges = split "\n", $swash->{'LIST'};
2977 for (my $i = 0; $i < @ranges; $i++) {
2978 my ($hex_begin, $hex_end, $map) = split "\t", $ranges[$i];
2979
2980 # The dm property has maps that are space separated sequences
2981 # of code points, as well as the special entry "<hangul
2982 # syllable>, which also contains a blank.
2983 my @map = split " ", $map;
2984 if (@map > 1) {
2985
2986 # If it's just the special entry, append as-is.
2987 if ($map eq '<hangul syllable>') {
2988 $list .= "$ranges[$i]\n";
2989 }
2990 else {
2991
2992 # These should all single-element ranges.
1a4c9760 2993 croak __PACKAGE__, "::prop_invmap: Not expecting a mapping with multiple code points in a multi-element range, $ranges[$i]" if $hex_end ne "" && $hex_end ne $hex_begin;
d11155ec
KW
2994
2995 # Convert them to decimal, as that's what's expected.
2996 $list .= "$hex_begin\t\t"
2997 . join(" ", map { hex } @map)
2998 . "\n";
2999 }
3000 next;
3001 }
3002
3003 # Here, the mapping doesn't have a blank, is for a single code
3004 # point.
34132297
KW
3005 my $begin = hex $hex_begin;
3006 my $end = (defined $hex_end && $hex_end ne "")
3007 ? hex $hex_end
3008 : $begin;
d11155ec
KW
3009
3010 # Again, the output is to be in decimal.
34132297 3011 my $decimal_map = hex $map;
d11155ec
KW
3012
3013 # We know that multi-element ranges with the same mapping
3014 # should not be adjusted, as after the adjustment
3015 # multi-element ranges are for consecutive increasing code
3016 # points. Further, the final element in the list won't be
3017 # adjusted, as there is nothing after it to include in the
3018 # adjustment
3019 if ($begin != $end || $i == @ranges -1) {
3020
3021 # So just convert these to single-element ranges
3022 foreach my $code_point ($begin .. $end) {
3023 $list .= sprintf("%04X\t\t%d\n",
3024 $code_point, $decimal_map);
3025 }
34132297 3026 }
d11155ec 3027 else {
34132297 3028
d11155ec
KW
3029 # Here, we have a candidate for adjusting. What we do is
3030 # look through the subsequent adjacent elements in the
3031 # input. If the map to the next one differs by 1 from the
3032 # one before, then we combine into a larger range with the
3033 # initial map. Loop doing this until we find one that
3034 # can't be combined.
3035
3036 my $offset = 0; # How far away are we from the initial
3037 # map
3038 my $squished = 0; # ? Did we squish at least two
3039 # elements together into one range
3040 for ( ; $i < @ranges; $i++) {
3041 my ($next_hex_begin, $next_hex_end, $next_map)
3042 = split "\t", $ranges[$i+1];
3043
3044 # In the case of 'dm', the map may be a sequence of
3045 # multiple code points, which are never combined with
3046 # another range
3047 last if $next_map =~ / /;
3048
3049 $offset++;
3050 my $next_decimal_map = hex $next_map;
3051
3052 # If the next map is not next in sequence, it
3053 # shouldn't be combined.
3054 last if $next_decimal_map != $decimal_map + $offset;
3055
3056 my $next_begin = hex $next_hex_begin;
3057
3058 # Likewise, if the next element isn't adjacent to the
3059 # previous one, it shouldn't be combined.
3060 last if $next_begin != $begin + $offset;
3061
3062 my $next_end = (defined $next_hex_end
3063 && $next_hex_end ne "")
3064 ? hex $next_hex_end
3065 : $next_begin;
3066
3067 # And finally, if the next element is a multi-element
3068 # range, it shouldn't be combined.
3069 last if $next_end != $next_begin;
3070
3071 # Here, we will combine. Loop to see if we should
3072 # combine the next element too.
3073 $squished = 1;
3074 }
3075
3076 if ($squished) {
3077
3078 # Here, 'i' is the element number of the last element to
3079 # be combined, and the range is single-element, or we
3080 # wouldn't be combining. Get it's code point.
3081 my ($hex_end, undef, undef) = split "\t", $ranges[$i];
3082 $list .= "$hex_begin\t$hex_end\t$decimal_map\n";
3083 } else {
3084
3085 # Here, no combining done. Just appen the initial
3086 # (and current) values.
3087 $list .= "$hex_begin\t\t$decimal_map\n";
3088 }
3089 }
3090 } # End of loop constructing the converted list
3091
3092 # Finish up the data structure for our converted swash
3093 my $type = ($second_try eq 'nfkccf') ? 'ToNFKCCF' : 'ToDm';
3094 $revised_swash{'LIST'} = $list;
3095 $revised_swash{'TYPE'} = $type;
3096 $revised_swash{'SPECIALS'} = $swash->{'SPECIALS'};
3097 $swash = \%revised_swash;
3098
3099 $utf8::SwashInfo{$type}{'missing'} = 0;
3100 $utf8::SwashInfo{$type}{'format'} = 'a';
62b3b855
KW
3101 }
3102 }
3103
3104 if ($swash->{'EXTRAS'}) {
3105 carp __PACKAGE__, "::prop_invmap: swash returned for $prop unexpectedly has EXTRAS magic";
3106 return;
3107 }
3108
3109 # Here, have a valid swash return. Examine it.
34132297 3110 my $returned_prop = $swash->{'TYPE'};
62b3b855
KW
3111
3112 # All properties but binary ones should have 'missing' and 'format'
3113 # entries
3114 $missing = $utf8::SwashInfo{$returned_prop}{'missing'};
3115 $missing = 'N' unless defined $missing;
3116
3117 $format = $utf8::SwashInfo{$returned_prop}{'format'};
3118 $format = 'b' unless defined $format;
3119
d11155ec
KW
3120 my $requires_adjustment = $format =~ /^a/;
3121
62b3b855
KW
3122 # The LIST input lines look like:
3123 # ...
3124 # 0374\t\tCommon
3125 # 0375\t0377\tGreek # [3]
3126 # 037A\t037D\tGreek # [4]
3127 # 037E\t\tCommon
3128 # 0384\t\tGreek
3129 # ...
3130 #
3131 # Convert them to like
3132 # 0374 => Common
3133 # 0375 => Greek
3134 # 0378 => $missing
3135 # 037A => Greek
3136 # 037E => Common
3137 # 037F => $missing
3138 # 0384 => Greek
3139 #
3140 # For binary properties, the final non-comment column is absent, and
3141 # assumed to be 'Y'.
3142
3143 foreach my $range (split "\n", $swash->{'LIST'}) {
3144 $range =~ s/ \s* (?: \# .* )? $ //xg; # rmv trailing space, comments
3145
3146 # Find the beginning and end of the range on the line
3147 my ($hex_begin, $hex_end, $map) = split "\t", $range;
3148 my $begin = hex $hex_begin;
3149 my $end = (defined $hex_end && $hex_end ne "")
3150 ? hex $hex_end
3151 : $begin;
3152
92bcf67b
KW
3153 # Each time through the loop (after the first):
3154 # $invlist[-2] contains the beginning of the previous range processed
3155 # $invlist[-1] contains the end+1 of the previous range processed
3156 # $invmap[-2] contains the value of the previous range processed
3157 # $invmap[-1] contains the default value for missing ranges ($missing)
3158 #
3159 # Thus, things are set up for the typical case of a new non-adjacent
3160 # range of non-missings to be added. But, if the new range is
dc8d8ea6 3161 # adjacent, it needs to replace the [-1] element; and if the new
92bcf67b
KW
3162 # range is a multiple value of the previous one, it needs to be added
3163 # to the [-2] map element.
3164
3165 # The first time through, everything will be empty. If the property
3166 # doesn't have a range that begins at 0, add one that maps to $missing
62b3b855
KW
3167 if (! @invlist) {
3168 if ($begin != 0) {
3169 push @invlist, 0;
3170 push @invmap, $missing;
3171 }
3172 }
e35c6019
KW
3173 elsif (@invlist > 1 && $invlist[-2] == $begin) {
3174
3175 # Here we handle the case where the input has multiple entries for
3176 # each code point. mktables should have made sure that each such
3177 # range contains only one code point. At this point, $invlist[-1]
3178 # is the $missing that was added at the end of the last loop
3179 # iteration, and [-2] is the last real input code point, and that
3180 # code point is the same as the one we are adding now, making the
3181 # new one a multiple entry. Add it to the existing entry, either
3182 # by pushing it to the existing list of multiple entries, or
3183 # converting the single current entry into a list with both on it.
3184 # This is all we need do for this iteration.
3185
3186 if ($end != $begin) {
294705a8 3187 croak __PACKAGE__, ":prop_invmap: Multiple maps per code point in '$prop' require single-element ranges: begin=$begin, end=$end, map=$map";
e35c6019
KW
3188 }
3189 if (! ref $invmap[-2]) {
3190 $invmap[-2] = [ $invmap[-2], $map ];
3191 }
3192 else {
3193 push @{$invmap[-2]}, $map;
3194 }
3195 $has_multiples = 1;
3196 next;
3197 }
62b3b855
KW
3198 elsif ($invlist[-1] == $begin) {
3199
3200 # If the input isn't in the most compact form, so that there are
3201 # two adjacent ranges that map to the same thing, they should be
d11155ec
KW
3202 # combined (EXCEPT where the arrays require adjustments, in which
3203 # case everything is already set up correctly). This happens in
3204 # our constructed dt mapping, as Element [-2] is the map for the
3205 # latest range so far processed. Just set the beginning point of
3206 # the map to $missing (in invlist[-1]) to 1 beyond where this
3207 # range ends. For example, in
62b3b855
KW
3208 # 12\t13\tXYZ
3209 # 14\t17\tXYZ
3210 # we have set it up so that it looks like
3211 # 12 => XYZ
3212 # 14 => $missing
3213 #
3214 # We now see that it should be
3215 # 12 => XYZ
3216 # 18 => $missing
d11155ec 3217 if (! $requires_adjustment && @invlist > 1 && ( (defined $map)
c887f93f
KW
3218 ? $invmap[-2] eq $map
3219 : $invmap[-2] eq 'Y'))
3220 {
62b3b855
KW
3221 $invlist[-1] = $end + 1;
3222 next;
3223 }
3224
3225 # Here, the range started in the previous iteration that maps to
3226 # $missing starts at the same code point as this range. That
3227 # means there is no gap to fill that that range was intended for,
3228 # so we just pop it off the parallel arrays.
3229 pop @invlist;
3230 pop @invmap;
3231 }
3232
3233 # Add the range beginning, and the range's map.
3234 push @invlist, $begin;
d11155ec 3235 if ($returned_prop eq 'ToDm') {
62b3b855
KW
3236
3237 # The decomposition maps are either a line like <hangul syllable>
3238 # which are to be taken as is; or a sequence of code points in hex
3239 # and separated by blanks. Convert them to decimal, and if there
3240 # is more than one, use an anonymous array as the map.
3241 if ($map =~ /^ < /x) {
3242 push @invmap, $map;
3243 }
3244 else {
bea2c146 3245 my @map = split " ", $map;
62b3b855
KW
3246 if (@map == 1) {
3247 push @invmap, $map[0];
3248 }
3249 else {
3250 push @invmap, \@map;
3251 }
3252 }
3253 }
3254 else {
3255
3256 # Otherwise, convert hex formatted list entries to decimal; add a
3257 # 'Y' map for the missing value in binary properties, or
3258 # otherwise, use the input map unchanged.
3259 $map = ($format eq 'x')
3260 ? hex $map
3261 : $format eq 'b'
3262 ? 'Y'
3263 : $map;
3264 push @invmap, $map;
3265 }
3266
3267 # We just started a range. It ends with $end. The gap between it and
3268 # the next element in the list must be filled with a range that maps
3269 # to the default value. If there is no gap, the next iteration will
3270 # pop this, unless there is no next iteration, and we have filled all
3271 # of the Unicode code space, so check for that and skip.
3272 if ($end < $MAX_UNICODE_CODEPOINT) {
3273 push @invlist, $end + 1;
3274 push @invmap, $missing;
3275 }
3276 }
3277
3278 # If the property is empty, make all code points use the value for missing
3279 # ones.
3280 if (! @invlist) {
3281 push @invlist, 0;
3282 push @invmap, $missing;
3283 }
3284
647396da 3285 # And add in standard element that all non-Unicode code points map to:
62b3b855
KW
3286 # $missing
3287 push @invlist, $MAX_UNICODE_CODEPOINT + 1;
3288 push @invmap, $missing;
3289
3290 # The second component of the map are those values that require
3291 # non-standard specification, stored in SPECIALS. These override any
3292 # duplicate code points in LIST. If we are using a proxy, we may have
3293 # already set $overrides based on the proxy.
3294 $overrides = $swash->{'SPECIALS'} unless defined $overrides;
3295 if ($overrides) {
3296
3297 # A negative $overrides implies that the SPECIALS should be ignored,
d11155ec 3298 # and a simple 'a' list is the value.
62b3b855 3299 if ($overrides < 0) {
d11155ec 3300 $format = 'a';
62b3b855
KW
3301 }
3302 else {
3303
3304 # Currently, all overrides are for properties that normally map to
3305 # single code points, but now some will map to lists of code
3306 # points (but there is an exception case handled below).
d11155ec 3307 $format = 'al';
62b3b855
KW
3308
3309 # Look through the overrides.
3310 foreach my $cp_maybe_utf8 (keys %$overrides) {
3311 my $cp;
3312 my @map;
3313
3314 # If the overrides came from SPECIALS, the code point keys are
3315 # packed UTF-8.
3316 if ($overrides == $swash->{'SPECIALS'}) {
3317 $cp = unpack("C0U", $cp_maybe_utf8);
3318 @map = unpack "U0U*", $swash->{'SPECIALS'}{$cp_maybe_utf8};
3319
3320 # The empty string will show up unpacked as an empty
3321 # array.
d11155ec 3322 $format = 'ale' if @map == 0;
62b3b855
KW
3323 }
3324 else {
3325
3326 # But if we generated the overrides, we didn't bother to
3327 # pack them, and we, so far, do this only for properties
d11155ec 3328 # that are 'a' ones.
62b3b855
KW
3329 $cp = $cp_maybe_utf8;
3330 @map = hex $overrides->{$cp};
d11155ec 3331 $format = 'a';
62b3b855
KW
3332 }
3333
3334 # Find the range that the override applies to.
3335 my $i = _search_invlist(\@invlist, $cp);
3336 if ($cp < $invlist[$i] || $cp >= $invlist[$i + 1]) {
294705a8 3337 croak __PACKAGE__, "::prop_invmap: wrong_range, cp=$cp; i=$i, current=$invlist[$i]; next=$invlist[$i + 1]"
62b3b855
KW
3338 }
3339
3340 # And what that range currently maps to
3341 my $cur_map = $invmap[$i];
3342
3343 # If there is a gap between the next range and the code point
3344 # we are overriding, we have to add elements to both arrays to
3345 # fill that gap, using the map that applies to it, which is
3346 # $cur_map, since it is part of the current range.
3347 if ($invlist[$i + 1] > $cp + 1) {
3348 #use feature 'say';
3349 #say "Before splice:";
3350 #say 'i-2=[', $i-2, ']', sprintf("%04X maps to %s", $invlist[$i-2], $invmap[$i-2]) if $i >= 2;
3351 #say 'i-1=[', $i-1, ']', sprintf("%04X maps to %s", $invlist[$i-1], $invmap[$i-1]) if $i >= 1;
3352 #say 'i =[', $i, ']', sprintf("%04X maps to %s", $invlist[$i], $invmap[$i]);
3353 #say 'i+1=[', $i+1, ']', sprintf("%04X maps to %s", $invlist[$i+1], $invmap[$i+1]) if $i < @invlist + 1;
3354 #say 'i+2=[', $i+2, ']', sprintf("%04X maps to %s", $invlist[$i+2], $invmap[$i+2]) if $i < @invlist + 2;
3355
3356 splice @invlist, $i + 1, 0, $cp + 1;
3357 splice @invmap, $i + 1, 0, $cur_map;
3358
3359 #say "After splice:";
3360 #say 'i-2=[', $i-2, ']', sprintf("%04X maps to %s", $invlist[$i-2], $invmap[$i-2]) if $i >= 2;
3361 #say 'i-1=[', $i-1, ']', sprintf("%04X maps to %s", $invlist[$i-1], $invmap[$i-1]) if $i >= 1;
3362 #say 'i =[', $i, ']', sprintf("%04X maps to %s", $invlist[$i], $invmap[$i]);
3363 #say 'i+1=[', $i+1, ']', sprintf("%04X maps to %s", $invlist[$i+1], $invmap[$i+1]) if $i < @invlist + 1;
3364 #say 'i+2=[', $i+2, ']', sprintf("%04X maps to %s", $invlist[$i+2], $invmap[$i+2]) if $i < @invlist + 2;
3365 }
3366
3367 # If the remaining portion of the range is multiple code
3368 # points (ending with the one we are replacing, guaranteed by
3369 # the earlier splice). We must split it into two
3370 if ($invlist[$i] < $cp) {
3371 $i++; # Compensate for the new element
3372
3373 #use feature 'say';
3374 #say "Before splice:";
3375 #say 'i-2=[', $i-2, ']', sprintf("%04X maps to %s", $invlist[$i-2], $invmap[$i-2]) if $i >= 2;
3376 #say 'i-1=[', $i-1, ']', sprintf("%04X maps to %s", $invlist[$i-1], $invmap[$i-1]) if $i >= 1;
3377 #say 'i =[', $i, ']', sprintf("%04X maps to %s", $invlist[$i], $invmap[$i]);
3378 #say 'i+1=[', $i+1, ']', sprintf("%04X maps to %s", $invlist[$i+1], $invmap[$i+1]) if $i < @invlist + 1;
3379 #say 'i+2=[', $i+2, ']', sprintf("%04X maps to %s", $invlist[$i+2], $invmap[$i+2]) if $i < @invlist + 2;
3380
3381 splice @invlist, $i, 0, $cp;
3382 splice @invmap, $i, 0, 'dummy';
3383
3384 #say "After splice:";
3385 #say 'i-2=[', $i-2, ']', sprintf("%04X maps to %s", $invlist[$i-2], $invmap[$i-2]) if $i >= 2;
3386 #say 'i-1=[', $i-1, ']', sprintf("%04X maps to %s", $invlist[$i-1], $invmap[$i-1]) if $i >= 1;
3387 #say 'i =[', $i, ']', sprintf("%04X maps to %s", $invlist[$i], $invmap[$i]);
3388 #say 'i+1=[', $i+1, ']', sprintf("%04X maps to %s", $invlist[$i+1], $invmap[$i+1]) if $i < @invlist + 1;
3389 #say 'i+2=[', $i+2, ']', sprintf("%04X maps to %s", $invlist[$i+2], $invmap[$i+2]) if $i < @invlist + 2;
3390 }
3391
3392 # Here, the range we are overriding contains a single code
3393 # point. The result could be the empty string, a single
3394 # value, or a list. If the last case, we use an anonymous
3395 # array.
3396 $invmap[$i] = (scalar @map == 0)
3397 ? ""
3398 : (scalar @map > 1)
3399 ? \@map
3400 : $map[0];
3401 }
3402 }
3403 }
3404 elsif ($format eq 'x') {
3405
647396da
KW
3406 # All hex-valued properties are really to code points, and have been
3407 # converted to decimal.
5bbfa552 3408 $format = 's';
62b3b855 3409 }
d11155ec
KW
3410 elsif ($returned_prop eq 'ToDm') {
3411 $format = 'ad';
62b3b855
KW
3412 }
3413 elsif ($format eq 'sw') { # blank-separated elements to form a list.
3414 map { $_ = [ split " ", $_ ] if $_ =~ / / } @invmap;
3415 $format = 'sl';
3416 }
3417 elsif ($returned_prop eq 'ToNameAlias') {
3418
3419 # This property currently doesn't have any lists, but theoretically
3420 # could
3421 $format = 'sl';
3422 }
b0b13ada 3423 elsif ($returned_prop eq 'ToPerlDecimalDigit') {
d11155ec 3424 $format = 'ae';
b0b13ada 3425 }
4f143a72
KW
3426 elsif ($returned_prop eq 'ToNv') {
3427
3428 # The one property that has this format is stored as a delta, so needs
3429 # to indicate that need to add code point to it.
3430 $format = 'ar';
3431 }
b577d4a6 3432 elsif ($format ne 'n' && $format ne 'a') {
62b3b855
KW
3433
3434 # All others are simple scalars
3435 $format = 's';
3436 }
e35c6019 3437 if ($has_multiples && $format !~ /l/) {
294705a8 3438 croak __PACKAGE__, "::prop_invmap: Wrong format '$format' for prop_invmap('$prop'); should indicate has lists";
e35c6019 3439 }
62b3b855
KW
3440
3441 return (\@invlist, \@invmap, $format, $missing);
3442}
3443
55d7b906 3444=head2 Unicode::UCD::UnicodeVersion
10a6ecd2 3445
a452d459
KW
3446This returns the version of the Unicode Character Database, in other words, the
3447version of the Unicode standard the database implements. The version is a
3448string of numbers delimited by dots (C<'.'>).
10a6ecd2
JH
3449
3450=cut
3451
3452my $UNICODEVERSION;
3453
3454sub UnicodeVersion {
3455 unless (defined $UNICODEVERSION) {
3456 openunicode(\$VERSIONFH, "version");
ce066323 3457 local $/ = "\n";
10a6ecd2
JH
3458 chomp($UNICODEVERSION = <$VERSIONFH>);
3459 close($VERSIONFH);
3460 croak __PACKAGE__, "::VERSION: strange version '$UNICODEVERSION'"
3461 unless $UNICODEVERSION =~ /^\d+(?:\.\d+)+$/;
3462 }
e80c2d9d 3463 $v_unicode_version = pack "C*", split /\./, $UNICODEVERSION;
10a6ecd2
JH
3464 return $UNICODEVERSION;
3465}
3aa957f9 3466
a452d459
KW
3467=head2 B<Blocks versus Scripts>
3468
3469The difference between a block and a script is that scripts are closer
3470to the linguistic notion of a set of code points required to present
3471languages, while block is more of an artifact of the Unicode code point
3472numbering and separation into blocks of (mostly) 256 code points.
3473
3474For example the Latin B<script> is spread over several B<blocks>, such
3475as C<Basic Latin>, C<Latin 1 Supplement>, C<Latin Extended-A>, and
3476C<Latin Extended-B>. On the other hand, the Latin script does not
3477contain all the characters of the C<Basic Latin> block (also known as
3478ASCII): it includes only the letters, and not, for example, the digits
3479or the punctuation.
3480
3481For blocks see L<http://www.unicode.org/Public/UNIDATA/Blocks.txt>
3482
3483For scripts see UTR #24: L<http://www.unicode.org/unicode/reports/tr24/>
3484
3485=head2 B<Matching Scripts and Blocks>
3486
3487Scripts are matched with the regular-expression construct
3488C<\p{...}> (e.g. C<\p{Tibetan}> matches characters of the Tibetan script),
f200dd12 3489while C<\p{Blk=...}> is used for blocks (e.g. C<\p{Blk=Tibetan}> matches
a452d459
KW
3490any of the 256 code points in the Tibetan block).
3491
430fe03d
KW
3492=head2 Old-style versus new-style block names
3493
3494Unicode publishes the names of blocks in two different styles, though the two
3495are equivalent under Unicode's loose matching rules.
3496
3497The original style uses blanks and hyphens in the block names (except for
3498C<No_Block>), like so:
3499
3500 Miscellaneous Mathematical Symbols-B
3501
3502The newer style replaces these with underscores, like this:
3503
3504 Miscellaneous_Mathematical_Symbols_B
3505
3506This newer style is consistent with the values of other Unicode properties.
3507To preserve backward compatibility, all the functions in Unicode::UCD that
3508return block names (except one) return the old-style ones. That one function,
3509L</prop_value_aliases()> can be used to convert from old-style to new-style:
3510
3511 my $new_style = prop_values_aliases("block", $old_style);
3512
3513Perl also has single-form extensions that refer to blocks, C<In_Cyrillic>,
3514meaning C<Block=Cyrillic>. These have always been written in the new style.
3515
3516To convert from new-style to old-style, follow this recipe:
3517
3518 $old_style = charblock((prop_invlist("block=$new_style"))[0]);
3519
3520(which finds the range of code points in the block using C<prop_invlist>,
3521gets the lower end of the range (0th element) and then looks up the old name
3522for its block using C<charblock>).
3523
7620cb10
KW
3524Note that starting in Unicode 6.1, many of the block names have shorter
3525synonyms. These are always given in the new style.
3526
8b731da2
JH
3527=head1 BUGS
3528
3529Does not yet support EBCDIC platforms.
3530
561c79ed
JH
3531=head1 AUTHOR
3532
a18e976f 3533Jarkko Hietaniemi. Now maintained by perl5 porters.
561c79ed
JH
3534
3535=cut
3536
35371;