blib/lib/Lingua/EN/NameCase.pm

filter: Statementstmt 100% 151 / 151 Branchbran 98.0% 49 / 50 Conditioncond 97.1% 34 / 35 MC/DCmcdc 84.2% 16 / 19 Subroutinesub 100% 20 / 20 Podpod 100% 2 / 2 totaltotal 98.1% 272 / 277 CC 37 SCAR 18.3
CC
37
Cov
99%
nc
12.0
NameCase
10.0
_i18n
6.0
CRAP 6.3
↑ Summary
1 package Lingua::EN::NameCase;
2  
3 =head1 NAME
4  
5 Lingua::EN::NameCase - Correctly case a person's name from UPPERCASE or lowercase
6  
7 =cut
8  
9 25 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 25 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 # Names are free text and may hold lone surrogates or code points beyond
13 # Unicode. Perl then warns from lc and friends; that is noise for the
14 # caller, who cannot fix it, so those warnings are off inside this module.
15 25 ▶no warnings 'utf8';
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 # Deliberately NOT "use locale". It made the result depend on the process
18 # locale: in the C locale (Windows code pages, bare containers) it gave
19 # "Emile" with an accent as "EMile", warned about every character above 255,
20 # and mis-cased "I" in Turkish. Unicode rules are the same everywhere.
21 25 ▶BEGIN {
Subroutine BEGIN: called CC=2 SCAR=7.1
22 # Make native 8-bit strings follow Unicode rules too (Perl 5.12 and later).
23 25 ▶ if ( $] >= 5.012 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($] >= "5.012") 25 0 25
24 25 require feature;
25 25 feature->import('unicode_strings');
26 }
27 }
28 25 ▶use autodie qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
29  
30 25 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
31 25 ▶use Exporter ();
Subroutine BEGIN: called CC=1 SCAR=0.0
32 25 ▶use List::Util qw(max);
Subroutine BEGIN: called CC=1 SCAR=0.0
33 25 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
34  
35 # Private routines. Sub::Private (enforce mode) makes a call from another
36 # package croak. It is optional: it needs a recent Perl and several modules,
37 # and the module is just as correct without it, so a missing Sub::Private
38 # means only that the internals are not locked.
39 24 ▶BEGIN {
Subroutine BEGIN: called CC=1 SCAR=0.0
40 24 eval {
41 24 require Sub::Private;
42 23 Sub::Private->import(
43 { mode => 'enforce' },
44 qw( _i18n _fail _safe_type _base_case _mac_case _particle_case _roman_case _postnominal_case )
45 );
46 23 1;
47 };
48 }
49  
50 24 our @ISA = qw( Exporter );
51 24 our @EXPORT = qw( nc );
52 24 our @EXPORT_OK = qw( NameCase nc );
53  
54 =head1 VERSION
55  
56 Version 1.22
57  
58 =cut
59  
60 24 our $VERSION = '1.22';
61  
62 =head1 SYNOPSIS
63  
64 use Lingua::EN::NameCase qw( nc NameCase );
65  
66 # Pattern 1: fix one name. nc() is like lc() and uc().
67 my $name = nc('JOHN O\'CALLAGHAN'); # "John O'Callaghan"
68 my $same = nc( \$name ); # a reference works too
69 # ($name itself is not changed)
70  
71 # Pattern 2: fix a list of names. You get a new list back.
72 my @clean = NameCase( 'ANNE JONES', 'BOB MCVEY' );
73  
74 # Pattern 3: fix an array in place.
75 my @names = ( 'ANNE JONES', 'BOB MCVEY' );
76 NameCase( \@names ); # @names is now fixed
77  
78 # Pattern 4: clean data read from a file or database.
79 open( my $fh, '<:encoding(UTF-8)', 'names.txt' );
80 while ( my $line = <$fh> ) {
81 chomp $line;
82 print nc($line), "\n";
83 }
84  
85 # Pattern 5: change the rules for part of your program only.
86 {
87 local $Lingua::EN::NameCase::SPANISH = 1; # keep "El" and "La"
88 print nc('EL PASO'); # "El Paso"
89 }
90 print nc('EL PASO'); # "el Paso"
91  
92 # Pattern 6: catch bad input.
93 eval { nc( { not => 'a name' } ) };
94 print "Problem: $@" if $@;
95  
96 # Other switches (all are package variables):
97 # $Lingua::EN::NameCase::HEBREW = 0; # "Ben" stays "Ben"
98 # $Lingua::EN::NameCase::ROMAN = 0; # "Li" stays "Li", not "LI"
99 # $Lingua::EN::NameCase::POSTNOMINAL = 0; # "PHD" becomes "Phd"
100  
101 =head1 DESCRIPTION
102  
103 Forenames and surnames are often stored either wholly in UPPERCASE
104 or wholly in lowercase. This module allows you to convert names into
105 the correct case where possible.
106  
107 Although forenames and surnames are normally stored separately if they
108 do appear in a single string, whitespace separated, NameCase and nc deal
109 correctly with them.
110  
111 NameCase currently correctly name cases names which include any of the
112 following:
113  
114 Mc, Mac, al, el, ap, da, de, delle, della, di, du, del, der,
115 la, le, lo, van and von.
116  
117 It correctly deals with names which contain apostrophes and hyphens too.
118  
119 =head2 EXAMPLE FIXES
120  
121 Original Name Case
122 -------- ---------
123 KEITH Keith
124 LEIGH-WILLIAMS Leigh-Williams
125 MCCARTHY McCarthy
126 O'CALLAGHAN O'Callaghan
127 ST. JOHN St. John
128  
129 plus "son (daughter) of" etc. in various languages, e.g.:
130  
131 VON STREIT von Streit
132 VAN DYKE van Dyke
133 AP LLWYD DAFYDD ap Llwyd Dafydd
134 etc.
135  
136 plus names with roman numerals (up to 89, LXXXIX), e.g.:
137  
138 henry viii Henry VIII
139 louis xiv Louis XIV
140  
141 =head2 CONFIGURATION
142  
143 The behaviour is controlled by package variables, read on every call
144 so they may be changed at any time:
145  
146 =over 4
147  
148 =item C<$Lingua::EN::NameCase::HEBREW> (default 1)
149  
150 Lowercase the Hebrew particles "ben" and "bat" when they follow another word.
151  
152 =item C<$Lingua::EN::NameCase::SPANISH> (default 0)
153  
154 Keep "El" and "La" capitalised (Spanish) instead of lowercasing them
155 (Greek and French).
156  
157 =item C<$Lingua::EN::NameCase::ROMAN> (default 1)
158  
159 Upper-case roman numerals (I to LXXXIX).
160  
161 =item C<$Lingua::EN::NameCase::POSTNOMINAL> (default 1)
162  
163 Normalise a trailing post-nominal such as "PhD" or "MBE".
164  
165 =item C<$Lingua::EN::NameCase::MAX_LENGTH> (default C<undef>, no limit)
166  
167 The longest name, in characters, that C<nc> will accept. A longer name makes
168 C<nc> croak with the C<too_long> message instead of using time and memory on
169 it. Set this when names come from an untrusted source.
170  
171 =item C<%Lingua::EN::NameCase::MESSAGES>
172  
173 Overrides the text of an error message by key (see L</MESSAGES> under
174 each routine). The text may contain C<{name}> placeholders, which are
175 replaced by the arguments given when the error is raised.
176 This is the hook for translating the error messages.
177  
178 =back
179  
180 =cut
181  
182 #--------------------------------------------------------------------------
183 # Public configuration. These are package variables (not lexicals) because
184 # they are a documented part of the API.
185  
186 24 our $HEBREW = 1;
187 24 our $SPANISH = 0;
188 24 our $ROMAN = 1;
189 24 our $POSTNOMINAL = 1;
190 24 our $MAX_LENGTH; # undef: no limit
191 24 our %MESSAGES;
192  
193 #--------------------------------------------------------------------------
194 # Constant data. Readonly guards against accidental modification; the hot
195 # path uses the pre-compiled structures built below, not these directly.
196  
197 # Error message templates, keyed by message id. Kept as templates so a
198 # translator can reorder the {placeholders}.
199 24 Readonly my %DEFAULT_MESSAGES => (
200 usage_nc => 'Usage: nc [[\\]$SCALAR] (got {got})',
201 usage_namecase => 'Usage: $SCALAR|@ARRAY = NameCase [\\]$SCALAR|@ARRAY (got {got})',
202 single_arg => 'NameCase only accepts a single scalar, array or array ref',
203 too_long => 'Name is too long: {length} characters (the maximum is {max})',
204 );
205  
206 # How a type name is shown in an error message: at most this many characters.
207 24 Readonly my $MAX_TYPE_NAME_LENGTH => 64;
208  
209 # Reference types the functions accept. (A plain hash: a Readonly hash is tied,
210 # which makes every lookup about ten times slower.)
211 24 my %ACCEPTED_REF = ( SCALAR => 1, ARRAY => 1 );
212  
213 # Name fragments after "Mac" that are normally NOT capitalised,
214 # e.g. Machado, Mackie. Matched as prefixes, as they always have been.
215 24 Readonly my @MAC_LOWERCASE_PREFIXES => qw(
216 Evicius Hado Har Hin Hlin Ias Iulis Kie Kle Klin Quarie Omber In
217 Kintosh Ken Hen Hiel Iol Kell Klem Krell Lin Key Kley Hell Hon
218 );
219  
220 # One regex for the list above: "Mac" followed by an exception.
221 # The compiled patterns below are plain lexicals, not Readonly: they are never
222 # changed, and matching through a Readonly scalar costs about 25% more.
223 24 my $MAC_EXCEPTION = do {
224 24 my $alternation = join '|', @MAC_LOWERCASE_PREFIXES;
225 24 qr{ \b Mac ($alternation) }x;
226 };
227  
228 # Particles that are lowercase whatever the context. Al and Van are only
229 # particles when another word follows, otherwise they are forenames.
230 24 my $ALWAYS_LOWER_PARTICLE = qr{
231 Al(?=\s++\w) # al, Arabic (or the forename Al)
232 | Ap\b # ap, Welsh
233 | Dell[ae]\b # della, delle, Italian
234 | D[aeiu]\b # da, de, di Italian; du French
235 | De[lr]\b # del Italian; der Dutch/Flemish
236 | L[eo]\b # lo Italian; le French
237 | Van(?=\s++\w) # van, German (or the forename Van)
238 | Von\b # von, Dutch/Flemish
239 }x;
240  
241 # Particles whose case depends on a configuration flag.
242 # "++" never gives back whitespace it has taken: that could not help and would
243 # cost time on a long run of spaces.
244 24 my $HEBREW_PARTICLE = qr{ (?<=\S\s) (?: Ben | Bat ) (?=\s++\w) }x;
245 24 my $SPANISH_CLASH = qr{ (?: El | La ) \b }x;
246  
247 # Roman numerals up to LXXXIX.
248 24 my $ROMAN_NUMERAL = qr{
249 (?= [XxLlIiVv] ) # at least one letter: the pattern below can also match nothing
250 (?: [Xx]{1,3} | [Xx][Ll] | [Ll][Xx]{0,3} )?
251 (?: [Ii]{1,3} | [Ii][VvXx] | [Vv][Ii]{0,3} )?
252 }x;
253  
254 # One pattern per setting of (HEBREW, SPANISH), so each name is scanned once
255 # instead of three times. Only the first letter of a particle is ever changed,
256 # so one pass gives the same answer as applying the rules one after another.
257 24 my %PARTICLE_PATTERN;
258 24 for my $hebrew ( 0, 1 ) {
259 48 for my $spanish ( 0, 1 ) {
260 96 my @alternatives = ($ALWAYS_LOWER_PARTICLE);
261 96 ▶ push @alternatives, $HEBREW_PARTICLE if $hebrew; # ben, bat after another word
Branch: 1 branch
BranchTrueFalseTotal
if $hebrew 48 48 96
262 96 ▶ push @alternatives, $SPANISH_CLASH if !$spanish; # el, la: Greek and French, not Spanish
Branch: 1 branch
BranchTrueFalseTotal
unless $spanish 48 48 96
263 96 my $any = join '|', @alternatives;
264 96 $PARTICLE_PATTERN{"$hebrew$spanish"} = qr{ \b ($any) }x;
265 }
266 }
267  
268 # Gate for the Mc/Mac rules. The last letter of the word must be checked as a
269 # letter: an older version let a space or punctuation stand in for it, so
270 # "Macdonalda Smith" passed the test that is meant to exclude names ending in
271 # a, c, i, o, z or j (typically Polish or Italian).
272 24 my $MAC_NAME = qr{
273 \b Mac # "Mac" at the start of a word,
274 [A-Za-z]{3,}+ # then three or more letters (Mack, Macy, Mace are too short),
275 (?<! [aciozj] ) # the last of them not one of a c i o z j,
276 \b # and the word ends there
277 | \b Mc # or "Mc" at the start of a word
278 }x;
279  
280 24 Readonly my @POST_NOMINAL_INITIALS => qw(
281 VC GC KG LG KT LT KP GCB OM GCSI GCMG GCIE GCVO GBE CH KCB DCB KCSI KCMG
282 DCMG KCIE KCVO DCVO KBE DBE CB CSI CMG CIE CVO CBE DSO LVO OBE ISO MVO MBE
283 IOM CGC RRC DSC MC DFC AFC ARRC OBI DCM CGM GM IDSM DSM MM DFM AFM SGM IOM
284 CPM QGM RVM BEM QPM QFSM QAM CPM MSM ERD VD TD UD ED RD VRD AE
285  
286 PC ADC QHP QHS QHDS QHNS QHC SCJ J LJ QS SL QC KC JP DL MP MSP MSYP AM AM
287 MLA MEP DBEnv DConstMgt DREst EdD DPhil PhD DLitt DSocSci MD EngD DD LLD
288 DProf MA MArch MAnth MSc MMORSE MMath MMathStat MPharm MPhil MSc MSci MSt
289 MRes MEng MChem MBiochem MSocSc MMus LLM BCL MPhys MComp MAcc MFin MBA MPA
290 MEd MEP MEnt MCGI MGeol MLitt MEarthSc MClinRes BA BSc LLB BEng MBChB FdA
291 FdSc FdEng PgDip PgD PgCert PgC PgCLTHE AUH AKC AUS HNC HNCert HND HNDip
292 DipHE Dip OND CertHE ACSM MCSM DIC AICSM ARSM ARCS LLB LLM BCL MJur DPhil
293 PhD LLD DipLP FCILEx GCILEx ACILEx CQSW DipSW BSW MSW FCILT CMILT MILT CPL
294 CTP CML PLS CTL DLP PLog EJLog ESLog EMLog JrLog Log SrLog BArch MArch ARB
295 RIBA RIAS RIAI RSAW MB BM BS BCh BChir MRCS FRCS MS MCh. MRCP FRCP MRCPCH
296 FRCPCH MRCPath MFPM FFPM BDS MRCPsych FRCPsych MRCOG FRCOG MCEM FCEM FRCA
297 FFPMRCA MRCGP FRCGP BSc MScChiro MChiro MSc DC LFHOM MFHOM FFHOM FADO FBDO
298 FCOptom MCOptom MOst DPT MCSP FCSP. SROT MSCR FSCR. CPhT RN VN RVN BVSc
299 BVetMed VetMB BVM&S MRCVS FRCVS FAWM PGCAP PGCHE PGCE PGDE BEd NPQH QTS
300 CSci CSciTeach RSci RSciTech CEng IEng EngTech ICTTech DEM MM CMarEng
301 CMarSci CMarTech IMarEng MarEngTech RGN SRN RMN RSCN SEN EN RNMH RN RM RN1
302 RNA RN2 RN3 RNMH RN4 RN5 RNLD RN6 RN8 RNC RN7 RN9 RHV RSN ROH RFHN SPAN
303 SPMH SPCN SPLD SPHP SCHM SCLD SPCC SPDN V100 V200 V300 LPE MSc
304 );
305  
306 # Built once at load time. Matching one alternation against the end of the
307 # name is far cheaper than the old loop of ~600 regex compilations per call.
308 # Later entries win a case-insensitive tie, as in the sequential original.
309 24 my %POST_NOMINAL_CANONICAL;
310 24 $POST_NOMINAL_CANONICAL{ lc $_ } = $_ for @POST_NOMINAL_INITIALS;
311  
312 # Finding a post-nominal "at the end" by scanning every word boundary costs time
313 # in proportion to the length of the name. Instead the name is reversed and the
314 # reversed entries are matched at the start, which takes the same time however
315 # long the name is. The entry must begin at a word boundary, so the character
316 # after it (in the reversed text) must not be a word character; every entry
317 # starts with a letter or digit, which makes that equivalent to the old \b.
318 24 my $POST_NOMINAL_REVERSED = do {
319 # Longest first, so the longest entry that fits wins, as before.
320 my $alternation = join '|',
321 24 map { quotemeta scalar reverse $_ } sort { length($b) <=> length($a) } keys %POST_NOMINAL_CANONICAL;
322 24 qr{
323 \A \n? # an optional newline that ended the name
324 ($alternation) # an entry (reversed), captured
325 (?!\w) # not preceded (in the original) by a word character
326 }xi;
327 };
328  
329 # How much of the end of a name can matter: the longest entry, a final newline
330 # and the character in front of the entry. Only this much is copied and
331 # reversed, so a huge name costs no more here than a short one.
332 24 my $POST_NOMINAL_WINDOW = 2 + max map { length } @POST_NOMINAL_INITIALS;
333  
334 #--------------------------------------------------------------------------
335 # Public functions
336  
337 =head1 COMMON PITFALLS
338  
339 =over 4
340  
341 =item * A scalar is never changed in place
342  
343 C<NameCase(\$name)> and C<nc(\$name)> read the string and return a new
344 one. Always use the return value: C<$name = nc($name);>.
345 Only an I<array reference> is changed in place.
346  
347 =item * Empty and undefined input
348  
349 C<undef>, an empty string and the string "0" are returned as they are.
350 No warning is given. Check for C<undef> yourself if you need to know.
351  
352 =item * Switches are global
353  
354 The four switches are package variables. If you change one, it changes for
355 the whole program until you change it back. Use C<local> inside a block
356 to limit the change.
357  
358 =item * Only the last word can be a post-nominal
359  
360 "JANE PHD SMITH" is not changed to "Jane PhD Smith". "SMITH PHD" is
361 changed to "Smith PhD".
362  
363 =item * One name per string, with no extra text
364  
365 "MR. AND MRS. SMITH" and similar text get the same treatment as a name.
366 Words like "Of" are not changed to "of".
367  
368 =item * The result is a guess
369  
370 Some names are cased wrongly. For example "MACINNES" becomes "Macinnes".
371 Check important data by hand. See L</LIMITATIONS>.
372  
373 =item * Wrong number of arguments
374  
375 C<nc> takes at most one argument. C<NameCase> in scalar context takes
376 exactly one. Anything else stops the program with an error message,
377 so wrap the call in C<eval> if the input is not trusted.
378  
379 =item * Untrusted input
380  
381 Set C<$Lingua::EN::NameCase::MAX_LENGTH> when names come from users. Without
382 it, a very large string is processed in full, using memory in proportion to
383 its size. A class name in an error message is shortened and any odd
384 character in it becomes "?".
385  
386 =item * C<nc()> with no argument uses C<$_>
387  
388 This is the same as the built-in C<lc>. It can surprise you inside a loop.
389  
390 =back
391  
392 =head1 ENCODING
393  
394 The module works on Perl character strings. Decode your input first,
395 for example with C<Encode::decode('UTF-8', $bytes)> or by reading a file
396 with C<< open(my $fh, '<:encoding(UTF-8)', $file) >>. Print the result
397 through an encoded handle, for example C<< binmode(STDOUT, ':encoding(UTF-8)') >>.
398  
399 =over 4
400  
401 =item * Safe (decoded characters)
402  
403 Accented letters ("EMILE ZOLA" with an accent), Greek and other alphabets
404 that have upper and lower case, and emojis. An emoji is left as it is,
405 and the words around it are fixed: C<john E<lt>emojiE<gt> smith> becomes
406 C<John E<lt>emojiE<gt> Smith>.
407  
408 =item * Not safe (raw bytes)
409  
410 A UTF-8 byte string that was not decoded. The ASCII letters are fixed, but
411 the bytes of non-ASCII letters are left alone and are not changed to
412 capitals.
413  
414 =item * Scripts without case
415  
416 Chinese, Japanese, Korean, Arabic, Hebrew and similar text is returned
417 unchanged. It is safe to pass in.
418  
419 =item * Apostrophes
420  
421 Only the plain apostrophe (C<'>) is understood in the 's rule.
422 "FRED'S" becomes "Fred's", but "FRED" followed by a curly apostrophe and "S"
423 becomes "Fred" followed by the curly apostrophe and a capital "S".
424  
425 =item * Sharp s
426  
427 The German sharp s at the start of a word becomes "Ss".
428  
429 =item * Error messages
430  
431 The built-in messages are plain ASCII English. Text you put in
432 C<%MESSAGES> may be any characters; use character strings.
433  
434 =back
435  
436 The module ignores the process locale (C<LC_ALL>, C<LC_CTYPE>): the result
437 is the same everywhere.
438  
439 =head1 FUNCTIONS
440  
441 =head2 NameCase
442  
443 Takes a scalar, scalarref, array or arrayref, and changes the case of the
444 contents, as appropriate. Essentially a wrapper around nc().
445  
446 =head3 PURPOSE
447  
448 Case one name, or a whole list of names, in one call.
449  
450 =head3 ARGS
451  
452 One scalar, one scalar reference, one array reference, or (in list context
453 only) a list of scalars.
454  
455 =head3 RETURNS
456  
457 =over 4
458  
459 =item * List context with a list, or an array reference
460  
461 A list of name-cased copies. The source is not modified.
462  
463 =item * Scalar or void context with an array reference
464  
465 The array is modified in place; the array reference is returned so calls
466 can be chained. The new names are stored into the existing elements, so a
467 reference to an element, or an array that aliases other variables (such as
468 C<\@_>), sees the change.
469  
470 =item * Scalar or scalar reference
471  
472 A name-cased copy. A scalar reference is I<not> modified (see L</LIMITATIONS>).
473 An undefined, empty or "0" value comes back unchanged.
474  
475 =back
476  
477 If the first argument is an array reference, any further arguments are
478 ignored. An empty array reference gives an empty list (or an unchanged
479 empty array). In list context a single scalar or scalar reference gives a
480 list of one name.
481  
482 =head3 SIDE EFFECTS
483  
484 Modifies the referenced array only in the in-place case above. If any
485 element is invalid, the function croaks and the array is left unchanged.
486 Dies (via L<Carp/croak>) on bad arguments.
487  
488 =head3 USAGE
489  
490 See L</SYNOPSIS>.
491  
492 =head3 EXAMPLE
493  
494 my @fixed = NameCase( 'JOHN SMITH', 'mary o\'neil' );
495 # ('John Smith', "Mary O'Neil")
496  
497 my @names = ( 'ANNE JONES', 'BOB MCVEY' );
498 NameCase( \@names );
499 # @names is now ('Anne Jones', 'Bob McVey')
500  
501 my $one = NameCase( 'DAVID VAN DYKE' ); # 'David van Dyke'
502  
503 =head3 API SPECIFICATION
504  
505 =head4 input
506  
507 {
508 names => {
509 type => 'arrayref', # list of scalars, or one [] / \scalar
510 optional => 0,
511 min => 1,
512 },
513 }
514  
515 A single hash reference, or any reference type other than SCALAR or ARRAY,
516 is rejected.
517  
518 Valid and invalid input, by partition:
519  
520 =over 4
521  
522 =item Argument form
523  
524 Valid: one string, one scalar reference (copied, not changed), one array
525 reference, or a list of strings. Invalid: no argument or, in scalar or
526 void context, more than one (croak C<single_arg>); a HASH, CODE, GLOB or
527 other reference (croak C<usage_namecase>).
528  
529 =item Array size
530  
531 0, 1, 2 and many are all valid. An empty array returns an empty result.
532 In list context the original is never changed. In scalar or void context
533 an array reference is changed in place and returned.
534  
535 =item Each element
536  
537 Must satisfy the C<nc> domain (see below), including C<$MAX_LENGTH>. One
538 bad element croaks, and then no element of the array is changed.
539  
540 =back
541  
542 The domain of each element is the domain of L</nc>.
543  
544 =head4 output
545  
546 { type => 'arrayref', element_type => 'string' } # list context
547 { type => 'string' } # one scalar
548 { type => 'arrayref' } # in place
549  
550 =head3 MESSAGES
551  
552 =over 4
553  
554 =item C<usage_namecase>
555  
556 I<Usage: $SCALAR|@ARRAY = NameCase [\]$SCALAR|@ARRAY (got {got})>.
557 The first argument was a reference of an unsupported type (C<{got}>).
558 Pass a scalar, a scalar ref or an array ref.
559  
560 =item C<single_arg>
561  
562 I<NameCase only accepts a single scalar, array or array ref>.
563 No arguments were given, or several were given in scalar context.
564 Pass exactly one value, or call in list context.
565  
566 =back
567  
568 =head3 PSEUDOCODE
569  
570 validate: reject refs that are neither ARRAY nor SCALAR
571 if list context and (more than one arg or an ARRAY ref):
572 return nc of each element
573 elsif ARRAY ref:
574 replace each element by nc(element); return the ref
575 elsif SCALAR ref:
576 return nc(dereferenced value)
577 elsif exactly one arg:
578 return nc(arg)
579 else:
580 croak single_arg
581  
582 =cut
583  
584 763 ▶sub NameCase {
Subroutine NameCase: called CC=10 SCAR=23.0
Pod documented
585 763 my $first = $_[0];
586 763 my $kind = ref $first; # '' for a plain scalar or no argument
587  
588 763 ▶ _fail( 'usage_namecase', { got => $kind } ) if $kind && !$ACCEPTED_REF{$kind};
Branch: 1 branch
BranchTrueFalseTotal
if $kind and not $ACCEPTED_REF{$kind} 38 725 763
Condition100%3/3
$kind and not $ACCEPTED_REF{$kind}
!ll&&!rl&&r
17754838
MC/DC100%2/2
$kind and not $ACCEPTED_REF{$kind}
$kind not $ACCEPTED_REF{$kind}
Truth table100%3/3
A and not(B)
A= $kindB= not $ACCEPTED_REF{$kind}
ABresult
0X0
100
111
589  
590 # We have an array, or several scalars, in list context: return a list.
591 725 ▶ if ( wantarray && ( @_ > 1 || $kind eq 'ARRAY' ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray and @_ > 1 || $kind eq "ARRAY") 82 643 725
Condition100%6/6
wantarray and @_ > 1 || $kind eq "ARRAY"
!ll&&!rl&&r
6301382
@_ > 1 or $kind eq "ARRAY"
l!l&&r!l&&!r
602213
MC/DC100%3/3
wantarray and @_ > 1 || $kind eq "ARRAY"
wantarray @_ > 1 $kind eq "ARRAY"
Truth table100%4/4
A and B or C
A= wantarrayB= @_ > 1C= $kind eq "ARRAY"
ABCresult
0XX0
1000
11X1
1011
592 82 ▶ return map { nc($_) } @{ $kind eq 'ARRAY' ? $first : \@_ };
Branch: 1 branch
BranchTrueFalseTotal
$kind eq 'ARRAY' ? : 25 57 82
593 }
594  
595 # An array ref in scalar/void context is converted in place, as that is
596 # the only way to be useful when no list is wanted. The whole answer is
597 # built first, so a bad element croaks before the caller's array is touched.
598 # It is then stored into the existing elements (a slice), not by replacing
599 # the array contents, so a caller's references to elements, and an array
600 # that aliases other variables (such as \@_), see the change.
601 643 ▶ if ( $kind eq 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "ARRAY") 511 132 643
602 511 my @fixed = map { nc($_) } @{$first};
603 262 @{$first}[ 0 .. $#fixed ] = @fixed;
604 262 return $first;
605 }
606  
607 # Scalar refs are copied, not modified (documented limitation).
608 132 ▶ return nc( ${$first} ) if $kind eq 'SCALAR';
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq "SCALAR" 11 121 132
609  
610 121 ▶ _fail('single_arg') unless @_ == 1;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ == 1 96 25 121
611 25 return nc($first);
612 }
613  
614 =head2 nc
615  
616 Takes a scalar or scalarref, and change the case of the name in the
617 corresponding string appropriately.
618  
619 =head3 PURPOSE
620  
621 Name-case a single string.
622  
623 =head3 ARGS
624  
625 Zero or one argument: a string or a scalar reference to a string.
626 With no argument, C<$_> is used (like C<lc> and C<uc>).
627  
628 =head3 RETURNS
629  
630 The name-cased string. An undefined, empty or "0" input is returned
631 unchanged. The input is never modified.
632  
633 =head3 SIDE EFFECTS
634  
635 None. Reads the package variables listed under L</CONFIGURATION>.
636 It does not change C<$_>, C<$@>, C<$!> or any C<alarm> timer.
637  
638 =head3 USAGE
639  
640 use Lingua::EN::NameCase qw(nc);
641 print nc('MR. JON WHITACRE III'); # Mr. Jon Whitacre III
642  
643 =head3 EXAMPLE
644  
645 nc('KEITH'); # 'Keith'
646 nc('o\'callaghan'); # "O'Callaghan"
647 nc('mccarthy'); # 'McCarthy'
648 nc(\ 'henry viii'); # 'Henry VIII'
649 nc('van der post'); # 'van der Post'
650  
651 local $Lingua::EN::NameCase::ROMAN = 0;
652 nc('na li'); # 'Na Li'
653  
654 =head3 API SPECIFICATION
655  
656 =head4 input
657  
658 {
659 name => {
660 type => 'string', # or a scalarref to a string
661 optional => 1, # defaults to $_
662 max => undef, # $MAX_LENGTH, when set
663 },
664 }
665  
666 Valid and invalid input, by partition:
667  
668 =over 4
669  
670 =item Argument count
671  
672 Valid: 0 (C<$_> is used) or 1. Invalid: 2 or more (croak C<usage_nc>,
673 reported as C<list>).
674  
675 =item Argument type
676  
677 Valid: a string, a number, a scalar reference, C<undef>, C<''> and C<'0'>
678 (the last three are returned unchanged). Invalid: any other reference
679 (HASH, ARRAY, CODE, GLOB, REF, Regexp, or an object); croak C<usage_nc>,
680 with the type or class name made safe and cut to 64 characters.
681  
682 =item Length (C<$MAX_LENGTH>)
683  
684 Counted in characters, never bytes. C<undef> means no limit. A length
685 equal to the maximum is accepted. One character more croaks C<too_long>.
686 A maximum of 0 admits only the false values. Negative or non-numeric
687 maximums are not checked; keep to non-negative integers.
688  
689 =item Text
690  
691 Any character string is accepted: ASCII, accented Latin, Greek, Cyrillic,
692 CJK, Hebrew, emoji, combining marks (Zalgo), and bidi controls such as
693 U+202E. None of these crash or lose characters. The result is at most 3
694 times as long as the input. Undecoded bytes are not cased.
695  
696 =item Recognised patterns
697  
698 C<Mac> is split when 3 or more letters follow and the last is not one of
699 C<a c i o z j>; C<Mc> is always split. Roman numerals I to LXXXIX are
700 converted; 90 (XC), IIII, XXXX and LXXXX are not. Post-nominals are
701 converted only at the end of the string.
702  
703 =back
704  
705 =head4 output
706  
707 { type => 'string', optional => 1 } # undef in, undef out
708  
709 =head3 MESSAGES
710  
711 =over 4
712  
713 =item C<usage_nc>
714  
715 I<Usage: nc [[\]$SCALAR] (got {got})>.
716 More than one argument, or a reference that is not a scalar reference,
717 was supplied (C<{got}> names the type). Pass one string or C<\$string>.
718  
719 =item C<too_long>
720  
721 I<Name is too long: {length} characters (the maximum is {max})>.
722 C<$MAX_LENGTH> is set and the name is longer. Shorten the input, or raise
723 the limit.
724  
725 =back
726  
727 =head3 PSEUDOCODE
728  
729 validate arguments (at most one; a plain scalar or SCALAR ref)
730 take the argument, or $_ when none was given
731 dereference it if it is a reference
732 return it at once if it is false (undef, '', '0')
733 lowercase it, capitalise each word, lowercase 's
734 apply the Mc/Mac rules
735 lowercase the particles (da, de, van, von, ...)
736 if ROMAN: upper-case roman numerals
737 if POSTNOMINAL: normalise a trailing PhD, MBE, ...
738 return the result
739  
740 =cut
741  
742 340980 ▶sub nc {
Subroutine nc: called CC=12 SCAR=24.8
Pod documented
743 # Read the argument exactly once. A tied variable could answer differently
744 # each time it is read, which would let a bad value slip past the check.
745 # With no argument we work on $_, so the caller's $_ is never modified,
746 # even when it holds a reference.
747 340980 ▶ my $name = @_ ? $_[0] : $_;
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 340961 19 340980
748 340980 my $kind = ref $name;
749  
750 340980 ▶ _fail( 'usage_nc', { got => $kind || 'list' } )
Branch: 1 branch
BranchTrueFalseTotal
if @_ > 1 or $kind and $kind ne "SCALAR" 179 340801 340980
Condition100%8/8
@_ > 1 or $kind and $kind ne "SCALAR"
l!l&&r!l&&!r
15164340801
$kind and $kind ne "SCALAR"
!ll&&!rl&&r
34076239164
$kind || 'list'
l!l
16613
MC/DC100%3/3
@_ > 1 or $kind and $kind ne "SCALAR"
@_ > 1 $kind $kind ne "SCALAR"
MC/DC100%1/1
$kind || 'list'
$kind
Truth table100%4/4
A or B and C
A= @_ > 1B= $kindC= $kind ne "SCALAR"
ABCresult
1XX1
0111
00X0
0100
Truth table100%2/2
A
A= $kind
Aresult
11
00
751 if @_ > 1 || ( $kind && $kind ne 'SCALAR' );
752  
753 340801 ▶ $name = ${$name} if $kind;
Branch: 1 branch
BranchTrueFalseTotal
if $kind 39 340762 340801
754  
755 # undef, '' and '0' have no case to fix.
756 340801 ▶ return $name unless $name;
Branch: 1 branch
BranchTrueFalseTotal
unless $name 668 340133 340801
757  
758 # Refuse oversize input before any copy of it is made.
759 340133 ▶ _fail( 'too_long', { length => length $name, max => $MAX_LENGTH } )
Branch: 1 branch
BranchTrueFalseTotal
if defined $Lingua::EN::NameCase::MAX_LENGTH and length $name > $Lingua::EN::NameCase::MAX_LENGTH 295 339838 340133
Condition100%3/3
defined $Lingua::EN::NameCase::MAX_LENGTH and length $name > $Lingua::EN::NameCase::MAX_LENGTH
!ll&&!rl&&r
339203635295
MC/DC100%2/2
defined $Lingua::EN::NameCase::MAX_LENGTH and length $name > $Lingua::EN::NameCase::MAX_LENGTH
defined $Lingua::EN::NameCase::MAX_LENGTH length $name > $Lingua::EN::NameCase::MAX_LENGTH
Truth table100%3/3
A and B
A= defined $Lingua::EN::NameCase::MAX_LENGTHB= length $name > $Lingua::EN::NameCase::MAX_LENGTH
ABresult
0X0
100
111
760 if defined $MAX_LENGTH && length $name > $MAX_LENGTH;
761  
762 339838 $name = _base_case($name);
763 339833 $name = _mac_case($name);
764 339827 $name = _particle_case($name);
765 339822 ▶ $name = _roman_case($name) if $ROMAN;
Branch: 1 branch
BranchTrueFalseTotal
if $Lingua::EN::NameCase::ROMAN 338866 956 339822
766 339817 ▶ $name = _postnominal_case($name) if $POSTNOMINAL;
Branch: 1 branch
BranchTrueFalseTotal
if $Lingua::EN::NameCase::POSTNOMINAL 339725 92 339817
767  
768 339812 return $name;
769 }
770  
771 #--------------------------------------------------------------------------
772 # Private functions (locked by Sub::Private when it is installed; see above).
773  
774 # Purpose: Raise a localised error.
775 # Entry: $key is a message id; $args is an optional hashref of
776 # placeholder values.
777 # Exit status: Never returns.
778 # Side effects: Croaks, reporting the error at the caller of the public
779 # function (Carp skips frames inside this package).
780 602 ▶sub _fail {
Subroutine _fail: called CC=5 SCAR=16.1
781 602 my ( $key, $args ) = @_;
782  
783 # The type name may come from an attacker (a class name can hold newlines
784 # or be megabytes long), so it is made safe before it reaches a log.
785 602 ▶ $args = { %{ $args || {} } };
Condition100%2/2
$args || {}
l!l
499103
MC/DC100%1/1
$args || {}
$args
Truth table100%2/2
A
A= $args
Aresult
11
00
786 602 ▶ $args->{got} = _safe_type( $args->{got} ) if defined $args->{got};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args->{"got"} 202 400 602
787  
788 # An empty or missing text would make a useless error: fall back to the id.
789 602 my $message = _i18n( $key, $args );
790 601 ▶ $message = $key unless defined $message && length $message;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $message and length $message 5 596 601
Condition100%3/3
defined $message and length $message
!ll&&!rl&&r
23596
MC/DC100%2/2
defined $message and length $message
defined $message length $message
Truth table100%3/3
A and B
A= defined $messageB= length $message
ABresult
0X0
100
111
791 601 croak $message;
792  
793 # Not reached: croak never returns. This stops a guard clause from
794 # falling through into bad data if croak is ever replaced.
795 # TODO: Unreachable code detected during path analysis. Investigate for removal.
796 24 die $message; ## no critic
797 }
798  
799 # Purpose: Make a reference type or class name safe to show in a message.
800 # Entry: $type is a string (possibly hostile).
801 # Exit status: Returns the string with every character other than a word
802 # character or colon replaced by "?", cut to a fixed length.
803 # Side effects: None.
804 207 ▶sub _safe_type {
Subroutine _safe_type: called CC=1 SCAR=0.0
805 207 my ($type) = @_;
806  
807 # Cut first, then clean: a class name can be megabytes long.
808 207 $type = substr $type, 0, $MAX_TYPE_NAME_LENGTH;
809 207 $type =~ s{ [^\w:] }{?}gx;
810  
811 207 return $type;
812 }
813  
814 # Purpose: Turn a message id into text, in the user's wording if they
815 # have supplied one in %MESSAGES.
816 # Entry: $key is a message id; $args is an optional hashref.
817 # Each {name} in the template is replaced by $args->{name};
818 # an unknown {name} is left as written.
819 # Exit status: Returns the message string; an unknown key is returned as is.
820 # Side effects: None.
821 620 ▶sub _i18n {
Subroutine _i18n: called CC=6 SCAR=17.9
822 620 my ( $key, $args ) = @_;
823  
824 # A missing key is a programming error, but it must not hide the real
825 # problem behind a second warning.
826 620 ▶ $key = 'unknown_message' unless defined $key;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $key 6 614 620
827 620 ▶ $args ||= {};
Condition100%2/2
$args ||= {}
l!l
6119
MC/DC100%1/1
$args ||= {}
$args
Truth table100%2/2
A
A= $args
Aresult
11
00
828 # Force a plain string: a reference here would become the exception itself.
829 620 ▶ my $template = '' . ( $MESSAGES{$key} // $DEFAULT_MESSAGES{$key} // $key );
Condition83%5/6
($Lingua::EN::NameCase::MESSAGES{$key} // $DEFAULT_MESSAGES{$key}) // $key
l!l&&r!l&&!r
609110
$Lingua::EN::NameCase::MESSAGES{$key} // $DEFAULT_MESSAGES{$key}
l!l&&r!l&&!r
2358611
MC/DC0%0/3
($Lingua::EN::NameCase::MESSAGES{$key} // $DEFAULT_MESSAGES{$key}) // $key
$Lingua::EN::NameCase::MESSAGES{$key} $DEFAULT_MESSAGES{$key} $key
Truth table75%3/4
A // B // C
A= $Lingua::EN::NameCase::MESSAGES{$key}B= $DEFAULT_MESSAGES{$key}C= $key
ABCresult
1XX1
01X1
0011
0000
830  
831 620 ▶ $template =~ s{ \{ (\w++) \} }{ $args->{$1} // "{$1}" }gex;
Condition100%2/2
$args->{$1} // "{$1}"
l!l
7997
MC/DC100%1/1
$args->{$1} // "{$1}"
$args->{$1}
Truth table100%2/2
A
A= $args->{$1}
Aresult
11
00
832  
833 620 return $template;
834 }
835  
836 # Purpose: Lowercase everything, capitalise each word, then undo the
837 # capital after an apostrophe (O'Neil stays, but Fred's -> Fred's).
838 # Entry: $name is a non-empty string.
839 # Exit status: Returns the converted string.
840 # Side effects: None.
841 339850 ▶sub _base_case {
Subroutine _base_case: called CC=1 SCAR=0.0
842 339850 my ($name) = @_;
843  
844 339850 $name = lc $name;
845 339850 $name =~ s{ \b (\w) }{\u$1}gx;
846 339850 $name =~ s{ (\'\w) \b }{\L$1}gx;
847  
848 339850 return $name;
849 }
850  
851 # Purpose: Fix Mc and Mac names, e.g. McDonald, MacDonald, but Machado.
852 # Entry: $name has been through _base_case().
853 # Exit status: Returns the converted string.
854 # Side effects: None.
855 339891 ▶sub _mac_case {
Subroutine _mac_case: called CC=2 SCAR=6.9
856 339891 my ($name) = @_;
857  
858 # Taken from NameParse.pm: only touch names that look like Mc/Mac names.
859 339891 ▶ if ( $name =~ $MAC_NAME ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($name =~ /$MAC_NAME/u) 433 339458 339891
860 433 $name =~ s{ \b (Ma?c) ([A-Za-z]) }{$1\u$2}gx;
861  
862 # Undo the capital for one-word exceptions such as Machado.
863 433 $name =~ s{$MAC_EXCEPTION}{Mac\l$1}g;
864 433 $name =~ s{ \b Macisaac }{MacIsaac}gx;
865 }
866 339891 $name =~ s{ \b Macmurdo }{MacMurdo}gx;
867  
868 339891 return $name;
869 }
870  
871 # Purpose: Lowercase "son of" particles: al, ap, da, de, del, van, von ...
872 # Entry: $name has been through _base_case().
873 # Exit status: Returns the converted string.
874 # Side effects: None.
875 339857 ▶sub _particle_case {
Subroutine _particle_case: called CC=3 SCAR=11.0
876 339857 my ($name) = @_;
877  
878 # Hebrew ben/bat need a preceding word, or "Ben Jones" would lose its
879 # capital: <http://www.jewfaq.org/jnames.htm>. El and La are lowercase in
880 # Greek and French, but not in Spanish. The pattern for the current
881 # switches was built at load time.
882 339857 ▶ my $pattern = $PARTICLE_PATTERN{ ( $HEBREW ? 1 : 0 ) . ( $SPANISH ? 1 : 0 ) };
Branch: 2 branches
BranchTrueFalseTotal
$Lingua::EN::NameCase::HEBREW ? : 339763 94 339857
$Lingua::EN::NameCase::SPANISH ? : 928 338929 339857
883 339857 $name =~ s{$pattern}{\l$1}g;
884  
885 339857 return $name;
886 }
887  
888 # Purpose: Upper-case roman numerals, e.g. Henry VIII.
889 # Entry: $name has been through _base_case().
890 # Exit status: Returns the converted string.
891 # Side effects: None.
892 338880 ▶sub _roman_case {
Subroutine _roman_case: called CC=1 SCAR=0.0
893 338880 my ($name) = @_;
894  
895 338880 $name =~ s{ \b ($ROMAN_NUMERAL) \b }{\U$1}gx;
896  
897 338880 return $name;
898 }
899  
900 # Purpose: Put a trailing post-nominal (PhD, MBE ...) into its usual case.
901 # Entry: $name has been through _base_case().
902 # Exit status: Returns the converted string.
903 # Side effects: None.
904 341371 ▶sub _postnominal_case {
Subroutine _postnominal_case: called CC=4 SCAR=13.9
905 341371 my ($name) = @_;
906  
907 341371 my $length = length $name;
908 341371 ▶ my $tail = $length > $POST_NOMINAL_WINDOW ? substr( $name, $length - $POST_NOMINAL_WINDOW ) : $name;
Branch: 1 branch
BranchTrueFalseTotal
$length > $POST_NOMINAL_WINDOW ? : 11194 330177 341371
909 341371 my $reversed = reverse $tail;
910  
911 341371 ▶ if ( $reversed =~ $POST_NOMINAL_REVERSED ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($reversed =~ /$POST_NOMINAL_REVERSED/u) 1730 339641 341371
912 # Offsets are in the reversed tail, which ends where the name ends.
913 1730 my ( $start, $end ) = ( $-[1], $+[1] );
914 1730 my $entry = lc scalar reverse substr( $reversed, $start, $end - $start );
915  
916 # A text can match only through case folding (the long s U+017F matches
917 # "s", the "fi" ligature matches "fi") and then has no exact key. It is
918 # left as it is: writing the missing value would delete the text.
919 1730 my $canonical = $POST_NOMINAL_CANONICAL{$entry};
920 1730 ▶ substr( $name, $length - $end, $end - $start ) = $canonical if defined $canonical;
Branch: 1 branch
BranchTrueFalseTotal
if defined $canonical 1658 72 1730
921 }
922  
923 341371 return $name;
924 }
925  
926 =head1 SECURITY
927  
928 The module only reads and builds strings. It opens no files, runs no
929 programs, uses no string C<eval>, and never turns its input into code or
930 into part of a regular expression. Notes for programs that use it:
931  
932 =over 4
933  
934 =item * Taint mode
935  
936 Taint is kept: a name that is tainted gives a tainted result. The module
937 never launders data and works under C<perl -T>.
938  
939 =item * Untrusted names
940  
941 Names from users can be very long. Set C<$Lingua::EN::NameCase::MAX_LENGTH>.
942 Case mapping can lengthen text: the result is at most three times as long as
943 the input. The length check is on the input, before the mapping.
944  
945 =item * Error messages
946  
947 The type or class name of a bad argument is cut to 64 characters and any
948 character other than a letter, digit, underscore or colon is shown as "?",
949 so a hostile class name cannot add lines or escape codes to a log.
950  
951 =item * Settings are global
952  
953 The switches, C<$MAX_LENGTH> and C<%MESSAGES> are package variables, so any
954 code in the same program can change them. Use C<local>. They are not a
955 security boundary.
956  
957 =item * Locked internals
958  
959 L<Sub::Private>, when installed, stops other packages calling the internal
960 routines. This is for tidiness, not security; it is switched off when the
961 environment variable C<HARNESS_ACTIVE> is true, and it is absent when
962 L<Sub::Private> is not installed.
963  
964 =item * Malformed text
965  
966 Invalid characters (lone surrogates, code points above U+10FFFF) are passed
967 through without a warning. Check the encoding of untrusted input before
968 calling this module.
969  
970 =back
971  
972 =head1 PERFORMANCE
973  
974 A typical name (two to four words) takes about 10 microseconds, which is
975 about 100,000 names a second, measured on an ordinary desktop with Perl 5.40.
976 The time grows in step with the length of the name. Each step is a small
977 number of regular expression passes over the name, and
978 the cost of each pass was measured and tuned:
979  
980 =over 4
981  
982 =item * The roman numeral and particle rules each make one pass.
983  
984 =item * A trailing post-nominal is found by matching the reversed name at its
985 start, so a very long name costs no more for this step than a short one.
986  
987 =item * Patterns are compiled once, when the module loads.
988  
989 =item * If L<Sub::Private> is installed each internal call is about 0.4
990 microseconds slower; this is the price of locking the internals.
991  
992 =back
993  
994 Set C<$Lingua::EN::NameCase::MAX_LENGTH> to bound the time spent on any one
995 name.
996  
997 =head1 LIMITATIONS
998  
999 The design choices below are known weaknesses.
1000  
1001 =over 4
1002  
1003 =item * Global configuration
1004  
1005 C<$HEBREW>, C<$SPANISH>, C<$ROMAN> and C<$POSTNOMINAL> are package
1006 variables, so one part of a program changing them changes the result for
1007 all of it. Use C<local> to scope a change. A per-call options hash would
1008 be better, but would change the API.
1009  
1010 =item * Scalar references are not modified in place
1011  
1012 C<NameCase(\$name)> returns a copy. Changing this would break existing
1013 callers.
1014  
1015 =item * Exceptions are prefixes
1016  
1017 The "Mac" exceptions match the start of a word, so MacInnes becomes
1018 Macinnes and MacKenzie becomes Mackenzie. An exact-surname list would be
1019 more accurate but needs data this module does not have.
1020  
1021 =item * Everything is an English-language heuristic
1022  
1023 Names are not cased by a grammar. "Ben" and "Van" are lowercased only when
1024 they follow another word, and every word of a name is treated alike
1025 (C<Estate Of Laura Jones>). For real name parsing use
1026 L<Lingua::EN::NameParse>.
1027  
1028 =item * Locale is ignored
1029  
1030 Case rules are the Unicode rules, whatever the locale. Older versions used
1031 C<use locale>, which gave different answers on different machines. Data in
1032 a legacy 8-bit code page must be decoded first (see L</ENCODING>). Language
1033 rules are not applied, so Turkish "I" becomes "i", not a dotless "i".
1034  
1035 =item * The Mac test covers the whole string
1036  
1037 Whether the "Mac" rules apply is decided once for the whole string, not word
1038 by word. A string that holds both a name such as "Mcdonald" and a name such
1039 as "Macchiato" will have both treated as Mac names. Pass one name at a time.
1040  
1041 =item * Hebrew particles need one space
1042  
1043 "ben" and "bat" are recognised only when exactly one white space character
1044 separates them from the word in front.
1045  
1046 =item * Post-nominals only at the end
1047  
1048 Only the last word is checked, and the list is not exhaustive.
1049 Since the entries are now matched literally, "MCh." and "FCSP." require
1050 their final dot (the dot used to match any character).
1051  
1052 =item * Error messages
1053  
1054 Messages are English templates with C<{name}> placeholders, replaceable
1055 through C<%MESSAGES>. There is no plural or gender handling because none
1056 of the messages needs it.
1057  
1058 =item * Encapsulation
1059  
1060 The internal routines are guarded with L<Sub::Private> in enforce mode, but
1061 only if that module is installed. It is optional because it needs Perl 5.14
1062 or later and heavy dependencies; without it the internals are ordinary
1063 subroutines whose names start with an underscore. L<Sub::Protected> is not
1064 used because the module has no classes or methods to protect.
1065  
1066 =back
1067  
1068 =head1 BUGS
1069  
1070 The module covers the rules that I know of. There are probably a lot
1071 more rules, exceptions etc. for "Western"-style languages which could be
1072 incorporated.
1073  
1074 There are probably lots of exceptions and problems - but as a general
1075 data 'cleaner' it may be all you need.
1076  
1077 Use Kim Ryan's L<Lingua::EN::NameParse> for any really sophisticated name parsing.
1078  
1079 =head1 SEE ALSO
1080  
1081 =over 4
1082  
1083 =item * L<Test Dashboard|https://nigelhorne.github.io/Lingua-EN-NameCase/coverage/>
1084  
1085 =back
1086  
1087 =head1 SUPPORT
1088  
1089 You can find documentation for this module with the perldoc command.
1090  
1091 perldoc Lingua::EN::NameCase
1092  
1093 You can also look for information at:
1094  
1095 =over 4
1096  
1097 =item * MetaCPAN
1098  
1099 L<https://metacpan.org/release/Lingua-EN-NameCase>
1100  
1101 =item * RT: CPAN's request tracker
1102  
1103 L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=Lingua-EN-NameCase>
1104  
1105 =item * CPANTS
1106  
1107 L<http://cpants.cpanauthors.org/dist/Lingua-EN-NameCase>
1108  
1109 =item * CPAN Testers' Matrix
1110  
1111 L<http://matrix.cpantesters.org/?dist=Lingua-EN-NameCase>
1112  
1113 =item * CPAN Testers Dependencies
1114  
1115 L<http://deps.cpantesters.org/?module=Lingua::EN::NameCase>
1116  
1117 =back
1118  
1119 =head1 AUTHOR
1120  
1121 1998-2014 Mark Summerfield <summer@qtrac.eu>
1122 2014-present Barbie <barbie@cpan.org>
1123  
1124 2020- Maintained by Nigel Horne, C<< <njh at nigelhorne.com> >>
1125  
1126 =head1 ACKNOWLEDGEMENTS
1127  
1128 Thanks to Kim Ryan <kimaryan@ozemail.com.au> for his Mc/Mac solution.
1129  
1130 =encoding utf8
1131  
1132 =head1 FORMAL SPECIFICATION
1133  
1134 This section is for readers who know Z notation. It is the only part of
1135 this file that is not plain ASCII. Each schema describes one function.
1136 A prime (') marks a value after the call. C<ARGS> is the list of arguments,
1137 C<ANY> is any Perl value, and C<STRING> is a Perl string.
1138  
1139 =head2 NameCase
1140  
1141 ┌─ NameCase ─────────────────────────────────────────────
1142 │ args? : seq ANY
1143 │ ctx? : { list, scalar, void }
1144 │ out! : seq STRING ∪ STRING ∪ ARRAYREF
1145 ├────────────────────────────────────────────────────────
1146 │ ref(head args?) ∉ { ARRAY, SCALAR, ∅ } ⇒ croak usage_namecase
1147 │ ctx? = list ∧ (#args? > 1 ∨ ref(head args?) = ARRAY)
1148 │ ⇒ out! = nc ∘ (elements args?)
1149 │ ctx? ≠ list ∧ ref(head args?) = ARRAY
1150 │ ⇒ head args? ' = nc ∘ (head args?) ∧ out! = head args?
1151 │ ref(head args?) = SCALAR ⇒ out! = nc(↑(head args?))
1152 │ ref(head args?) = ∅ ∧ #args? = 1 ⇒ out! = nc(head args?)
1153 │ otherwise ⇒ croak single_arg
1154 └────────────────────────────────────────────────────────
1155  
1156 =head2 nc
1157  
1158 ┌─ nc ───────────────────────────────────────────────────
1159 │ name? : STRING ∪ ↑STRING ∪ {⊥}
1160 │ out! : STRING ∪ {⊥}
1161 ├────────────────────────────────────────────────────────
1162 │ #args > 1 ∨ ref(name?) ∉ { ∅, SCALAR } ⇒ croak usage_nc
1163 │ MAX_LENGTH ≠ ⊥ ∧ value ∉ {⊥, "", "0"} ∧ #value > MAX_LENGTH ⇒ croak too_long
1164 │ value = (name? ∈ ↑STRING ⇒ ↑name? ∨ name?)
1165 │ value ∈ {⊥, "", "0"} ⇒ out! = value
1166 │ otherwise
1167 │ out! = postnominal ∘ roman ∘ particles ∘ mac ∘ base (value)
1168 │ where roman and postnominal apply only when enabled
1169 └────────────────────────────────────────────────────────
1170  
1171 =head2 Configuration
1172  
1173 ┌─ Config ───────────────────────────────────────────────
1174 │ HEBREW, SPANISH, ROMAN, POSTNOMINAL : { 0, 1 }
1175 │ MAX_LENGTH : ℕ ∪ {⊥}
1176 │ MESSAGES : KEY ⇸ STRING
1177 └────────────────────────────────────────────────────────
1178 ┌─ Init ─────────────────────────────────────────────────
1179 │ Config'
1180 ├────────────────────────────────────────────────────────
1181 │ HEBREW' = 1 ∧ SPANISH' = 0 ∧ ROMAN' = 1 ∧ POSTNOMINAL' = 1
1182 │ MESSAGES' = ∅ ∧ MAX_LENGTH' = ⊥
1183 └────────────────────────────────────────────────────────
1184 ┌─ Set ──────────────────────────────────────────────────
1185 │ ΔConfig ; flag? : { HEBREW, SPANISH, ROMAN, POSTNOMINAL } ; v? : { 0, 1 }
1186 ├────────────────────────────────────────────────────────
1187 │ flag?' = v? ∧ all other variables are unchanged
1188 └────────────────────────────────────────────────────────
1189  
1190 nc and NameCase read Config and never change it (ΞConfig).
1191  
1192 =head1 STATE DIAGRAM
1193  
1194 The module keeps no data between calls except the configuration. So there
1195 are two small machines: the configuration, and what happens during one call.
1196  
1197 Configuration (the four switches, C<$MAX_LENGTH> and C<%MESSAGES>):
1198  
1199 use Lingua::EN::NameCase
1200 |
1201 v
1202 +-----------------+ set a switch or %MESSAGES key +-----------------+
1203 | DEFAULTS |---------------------------------->| CUSTOMISED |
1204 | HEBREW=1 | action: later calls use it | any switch or |
1205 | SPANISH=0 |<----------------------------------| message differs |
1206 | ROMAN=1 | set back, or leave a block +-----------------+
1207 | POSTNOMINAL=1 | that used "local" | ^
1208 +-----------------+ +----------+
1209 set again
1210  
1211 DEFAULTS also means that C<$MAX_LENGTH> is C<undef> and C<%MESSAGES> is
1212 empty. Both states accept every call below. Calls never change the
1213 configuration.
1214  
1215 One call to C<nc> or C<NameCase>:
1216  
1217 nc(...) / NameCase(...)
1218 |
1219 v
1220 +------------+ bad type, wrong count +----------+
1221 | VALIDATING |------------------------->| FAILED |
1222 +------------+ action: croak with the +----------+
1223 | message (usage_nc, (the caller
1224 | ok usage_namecase, gets an
1225 v single_arg) exception)
1226 +------------+ undef, "" or "0" +----------+
1227 | READING |------------------------->| DONE |
1228 +------------+ action: return it as is +----------+
1229 | ^
1230 | has text |
1231 v |
1232 +------------+ base case, Mc/Mac, particles, |
1233 | CASING | roman numerals (if ROMAN), |
1234 +------------+ post-nominal (if POSTNOMINAL) |
1235 | |
1236 +---------------------------------------+
1237 action: return the new string
1238  
1239 READING also goes to FAILED when $MAX_LENGTH is set and the text is
1240 longer (message too_long). The caller gets an exception and nothing
1241 is changed.
1242  
1243 NameCase only: an array ref in scalar or void context goes from
1244 CASING to DONE after replacing each element (the only side effect
1245 on caller data), and returns the array ref.
1246  
1247 =head1 LICENSE AND COPYRIGHT
1248  
1249 Copyright (c) Mark Summerfield 1998-2014. All Rights Reserved.
1250 Copyright (c) Barbie 2014-2015. All Rights Reserved.
1251 Copyright (c) Nigel Horne 2020-2026. All Rights Reserved.
1252  
1253 This distribution is free software; you can redistribute it and/or
1254 modify it under the Artistic License 2.0.
1255  
1256 =cut
1257  
1258 24 1;
↑ Summary