lib/Lingua/EN/NameCase.pm

Structural Coverage (Approximate)

TER1 (Statement): 98.18%
TER2 (Branch): 97.92%
TER3 (LCSAJ): 100.0% (5/5)
Approximate LCSAJ segments: 49

LCSAJ Legend

โ— Covered โ€” this LCSAJ path was executed during testing.

โ— Not covered โ€” this LCSAJ path was never executed. These are the paths to focus on.

Multiple dots on a line indicate that multiple control-flow paths begin at that line. Hovering over any dot shows:

        start โ†’ end โ†’ jump
        

Uncovered paths show [NOT COVERED] in the tooltip.

Mutant Testing Legend

Survived (tests missed this) Killed (tests detected this) No mutation
    1: package Lingua::EN::NameCase;
    2: 
    3: use strict;
    4: use warnings;
    5: 
    6: # TODO: _fail: remove the unreachable die (and its path-analysis TODO), or turn that TODO into a plain comment
    7: # TODO: POD LIMITATIONS/Encapsulation says Sub::Private needs Perl 5.14; it is 5.26+ (match CLAUDE.md and cpanfile)
    8: # TODO: Mutants NUM_BOUNDARY_23_10 (>=, >, <, <= on the `$] >= 5.012` test) survive: mark as equivalent or add a unicode_strings test for native 8-bit strings
    9: # TODO: Devel::Cover reports 1 branch, 2 condition and 2 statement errors: re-run after removing the unreachable die and document or cover the rest
   10: # TODO: Decide whether these are bugs or documented traits, then add tests and COMMON PITFALLS text: nc('MARY LI') -> 'Mary LI', nc('LIV TYLER') -> 'LIV Tyler', nc('MACINTYRE') -> 'Macintyre', nc('MACKENZIE') -> 'Mackenzie', nc('McDonald MacChiato') -> both treated as Mac names
   11: # TODO: API SPECIFICATION (NameCase and nc): add one line on decoded characters versus undecoded bytes
   12: # TODO: Check that t/fuzz.t and t/all-fuzz.t skip cleanly when App::Test::Generator or fuzz-harness-generator is missing
   13: #
   14: # Post-release roadmap:
   15: # TODO: Replace the Mac prefix match with an exact-surname table (MacIntyre, MacKenzie, MacInnes right; Machado stays lowercase)
   16: # TODO: Per-call options: nc($name, \%opts) or an object (->new(spanish => 1)) instead of global package variables; keep the globals as defaults
   17: # TODO: Decide Mac/Mc per word instead of for the whole string
   18: # TODO: More particles and affixes: ten, ter, te, van de; y, dos, das, do; Fitz, Ni, Ui, Mac an; Scandinavian forms
   19: # TODO: Roman numerals: convert only when last or after a forename, so Li and Liv are safe by default
   20: # TODO: User-supplied exceptions hash (%EXCEPTIONS: DeShawn, LaToya, McKay) that overrides the rules
   21: # TODO: Streaming and bulk API (nc_file or an iterator); consider speed work only if batches justify it
   22: # TODO: Opt-in Turkish dotted/dotless I; Dutch ij; check hyphenated and apostrophe forms such as D'Angelo and O'Neill-Jones
   23: # TODO: Integrations: DBIx::Class or Mojolicious filter/helper; a command-line nc script reading standard input
   24: # TODO: Property-based tests: idempotence nc(nc(x)) eq nc(x), output at most 3x input length, only the case of letters changes
   25: # TODO: Housekeeping: prune dated coverage_history snapshots
   26: 
   27: =head1 NAME
   28: 
   29: Lingua::EN::NameCase - Correctly case a person's name from UPPERCASE or lowercase
   30: 
   31: =cut
   32: 
   33: # Names are free text and may hold lone surrogates or code points beyond
   34: # Unicode.  Perl then warns from lc and friends; that is noise for the
   35: # caller, who cannot fix it, so those warnings are off inside this module.
   36: no warnings 'utf8';
   37: 
   38: # Deliberately NOT "use locale".  It made the result depend on the process
   39: # locale: in the C locale (Windows code pages, bare containers) it gave
   40: # "Emile" with an accent as "EMile", warned about every character above 255,
   41: # and mis-cased "I" in Turkish.  Unicode rules are the same everywhere.
   42: BEGIN {
   43: 	# Make native 8-bit strings follow Unicode rules too (Perl 5.12 and later).
โ—44 โ†’ 44 โ†’ 0   44: 	if ( $] >= 5.012 ) {

					
Mutants (Total: 4, Killed: 1, Survived: 3)
45: require feature; 46: feature->import('unicode_strings'); 47: } 48: } 49: use autodie qw(:all); 50: 51: use Carp qw(croak); 52: use Exporter (); 53: use List::Util qw(max); 54: use Readonly; 55: 56: # Private routines. Sub::Private (enforce mode) makes a call from another 57: # package croak. It is optional: it needs a recent Perl and several modules, 58: # and the module is just as correct without it, so a missing Sub::Private 59: # means only that the internals are not locked. 60: BEGIN { 61: eval { 62: require Sub::Private; 63: Sub::Private->import( 64: { mode => 'enforce' }, 65: qw( _i18n _fail _safe_type _base_case _mac_case _particle_case _roman_case _postnominal_case ) 66: ); 67: 1; 68: }; 69: } 70: 71: our @ISA = qw( Exporter ); 72: our @EXPORT = qw( nc ); 73: our @EXPORT_OK = qw( NameCase nc ); 74: 75: =head1 VERSION 76: 77: Version 1.22 78: 79: =cut 80: 81: our $VERSION = '1.22'; 82: 83: =head1 SYNOPSIS 84: 85: use Lingua::EN::NameCase qw( nc NameCase ); 86: 87: # Pattern 1: fix one name. nc() is like lc() and uc(). 88: my $name = nc('JOHN O\'CALLAGHAN'); # "John O'Callaghan" 89: my $same = nc( \$name ); # a reference works too 90: # ($name itself is not changed) 91: 92: # Pattern 2: fix a list of names. You get a new list back. 93: my @clean = NameCase( 'ANNE JONES', 'BOB MCVEY' ); 94: 95: # Pattern 3: fix an array in place. 96: my @names = ( 'ANNE JONES', 'BOB MCVEY' ); 97: NameCase( \@names ); # @names is now fixed 98: 99: # Pattern 4: clean data read from a file or database. 100: open( my $fh, '<:encoding(UTF-8)', 'names.txt' ); 101: while ( my $line = <$fh> ) { 102: chomp $line; 103: print nc($line), "\n"; 104: } 105: 106: # Pattern 5: change the rules for part of your program only. 107: { 108: local $Lingua::EN::NameCase::SPANISH = 1; # keep "El" and "La" 109: print nc('EL PASO'); # "El Paso" 110: } 111: print nc('EL PASO'); # "el Paso" 112: 113: # Pattern 6: catch bad input. 114: eval { nc( { not => 'a name' } ) }; 115: print "Problem: $@" if $@; 116: 117: # Other switches (all are package variables): 118: # $Lingua::EN::NameCase::HEBREW = 0; # "Ben" stays "Ben" 119: # $Lingua::EN::NameCase::ROMAN = 0; # "Li" stays "Li", not "LI" 120: # $Lingua::EN::NameCase::POSTNOMINAL = 0; # "PHD" becomes "Phd" 121: 122: =head1 DESCRIPTION 123: 124: Forenames and surnames are often stored either wholly in UPPERCASE 125: or wholly in lowercase. This module allows you to convert names into 126: the correct case where possible. 127: 128: Although forenames and surnames are normally stored separately if they 129: do appear in a single string, whitespace separated, NameCase and nc deal 130: correctly with them. 131: 132: NameCase currently correctly name cases names which include any of the 133: following: 134: 135: Mc, Mac, al, el, ap, da, de, delle, della, di, du, del, der, 136: la, le, lo, van and von. 137: 138: It correctly deals with names which contain apostrophes and hyphens too. 139: 140: =head2 EXAMPLE FIXES 141: 142: Original Name Case 143: -------- --------- 144: KEITH Keith 145: LEIGH-WILLIAMS Leigh-Williams 146: MCCARTHY McCarthy 147: O'CALLAGHAN O'Callaghan 148: ST. JOHN St. John 149: 150: plus "son (daughter) of" etc. in various languages, e.g.: 151: 152: VON STREIT von Streit 153: VAN DYKE van Dyke 154: AP LLWYD DAFYDD ap Llwyd Dafydd 155: etc. 156: 157: plus names with roman numerals (up to 89, LXXXIX), e.g.: 158: 159: henry viii Henry VIII 160: louis xiv Louis XIV 161: 162: =head2 CONFIGURATION 163: 164: The behaviour is controlled by package variables, read on every call 165: so they may be changed at any time: 166: 167: =over 4 168: 169: =item C<$Lingua::EN::NameCase::HEBREW> (default 1) 170: 171: Lowercase the Hebrew particles "ben" and "bat" when they follow another word. 172: 173: =item C<$Lingua::EN::NameCase::SPANISH> (default 0) 174: 175: Keep "El" and "La" capitalised (Spanish) instead of lowercasing them 176: (Greek and French). 177: 178: =item C<$Lingua::EN::NameCase::ROMAN> (default 1) 179: 180: Upper-case roman numerals (I to LXXXIX). 181: 182: =item C<$Lingua::EN::NameCase::POSTNOMINAL> (default 1) 183: 184: Normalise a trailing post-nominal such as "PhD" or "MBE". 185: 186: =item C<$Lingua::EN::NameCase::MAX_LENGTH> (default C<undef>, no limit) 187: 188: The longest name, in characters, that C<nc> will accept. A longer name makes 189: C<nc> croak with the C<too_long> message instead of using time and memory on 190: it. Set this when names come from an untrusted source. 191: 192: =item C<%Lingua::EN::NameCase::MESSAGES> 193: 194: Overrides the text of an error message by key (see L</MESSAGES> under 195: each routine). The text may contain C<{name}> placeholders, which are 196: replaced by the arguments given when the error is raised. 197: This is the hook for translating the error messages. 198: 199: =back 200: 201: =cut 202: 203: #-------------------------------------------------------------------------- 204: # Public configuration. These are package variables (not lexicals) because 205: # they are a documented part of the API. 206: 207: our $HEBREW = 1; 208: our $SPANISH = 0; 209: our $ROMAN = 1; 210: our $POSTNOMINAL = 1; 211: our $MAX_LENGTH; # undef: no limit 212: our %MESSAGES; 213: 214: #-------------------------------------------------------------------------- 215: # Constant data. Readonly guards against accidental modification; the hot 216: # path uses the pre-compiled structures built below, not these directly. 217: 218: # Error message templates, keyed by message id. Kept as templates so a 219: # translator can reorder the {placeholders}. 220: Readonly my %DEFAULT_MESSAGES => ( 221: usage_nc => 'Usage: nc [[\\]$SCALAR] (got {got})', 222: usage_namecase => 'Usage: $SCALAR|@ARRAY = NameCase [\\]$SCALAR|@ARRAY (got {got})', 223: single_arg => 'NameCase only accepts a single scalar, array or array ref', 224: too_long => 'Name is too long: {length} characters (the maximum is {max})', 225: ); 226: 227: # How a type name is shown in an error message: at most this many characters. 228: Readonly my $MAX_TYPE_NAME_LENGTH => 64; 229: 230: # Reference types the functions accept. (A plain hash: a Readonly hash is tied, 231: # which makes every lookup about ten times slower.) 232: my %ACCEPTED_REF = ( SCALAR => 1, ARRAY => 1 ); 233: 234: # Name fragments after "Mac" that are normally NOT capitalised, 235: # e.g. Machado, Mackie. Matched as prefixes, as they always have been. 236: Readonly my @MAC_LOWERCASE_PREFIXES => qw( 237: Evicius Hado Har Hin Hlin Ias Iulis Kie Kle Klin Quarie Omber In 238: Kintosh Ken Hen Hiel Iol Kell Klem Krell Lin Key Kley Hell Hon 239: ); 240: 241: # One regex for the list above: "Mac" followed by an exception. 242: # The compiled patterns below are plain lexicals, not Readonly: they are never 243: # changed, and matching through a Readonly scalar costs about 25% more. 244: my $MAC_EXCEPTION = do { 245: my $alternation = join '|', @MAC_LOWERCASE_PREFIXES; 246: qr{ \b Mac ($alternation) }x; 247: }; 248: 249: # Particles that are lowercase whatever the context. Al and Van are only 250: # particles when another word follows, otherwise they are forenames. 251: my $ALWAYS_LOWER_PARTICLE = qr{ 252: Al(?=\s++\w) # al, Arabic (or the forename Al) 253: | Ap\b # ap, Welsh 254: | Dell[ae]\b # della, delle, Italian 255: | D[aeiu]\b # da, de, di Italian; du French 256: | De[lr]\b # del Italian; der Dutch/Flemish 257: | L[eo]\b # lo Italian; le French 258: | Van(?=\s++\w) # van, German (or the forename Van) 259: | Von\b # von, Dutch/Flemish 260: }x; 261: 262: # Particles whose case depends on a configuration flag. 263: # "++" never gives back whitespace it has taken: that could not help and would 264: # cost time on a long run of spaces. 265: my $HEBREW_PARTICLE = qr{ (?<=\S\s) (?: Ben | Bat ) (?=\s++\w) }x; 266: my $SPANISH_CLASH = qr{ (?: El | La ) \b }x; 267: 268: # Roman numerals up to LXXXIX. 269: my $ROMAN_NUMERAL = qr{ 270: (?= [XxLlIiVv] ) # at least one letter: the pattern below can also match nothing 271: (?: [Xx]{1,3} | [Xx][Ll] | [Ll][Xx]{0,3} )? 272: (?: [Ii]{1,3} | [Ii][VvXx] | [Vv][Ii]{0,3} )? 273: }x; 274: 275: # One pattern per setting of (HEBREW, SPANISH), so each name is scanned once 276: # instead of three times. Only the first letter of a particle is ever changed, 277: # so one pass gives the same answer as applying the rules one after another. 278: my %PARTICLE_PATTERN; 279: for my $hebrew ( 0, 1 ) { 280: for my $spanish ( 0, 1 ) { 281: my @alternatives = ($ALWAYS_LOWER_PARTICLE); 282: push @alternatives, $HEBREW_PARTICLE if $hebrew; # ben, bat after another word 283: push @alternatives, $SPANISH_CLASH if !$spanish; # el, la: Greek and French, not Spanish 284: my $any = join '|', @alternatives; 285: $PARTICLE_PATTERN{"$hebrew$spanish"} = qr{ \b ($any) }x; 286: } 287: } 288: 289: # Gate for the Mc/Mac rules. The last letter of the word must be checked as a 290: # letter: an older version let a space or punctuation stand in for it, so 291: # "Macdonalda Smith" passed the test that is meant to exclude names ending in 292: # a, c, i, o, z or j (typically Polish or Italian). 293: my $MAC_NAME = qr{ 294: \b Mac # "Mac" at the start of a word, 295: [A-Za-z]{3,}+ # then three or more letters (Mack, Macy, Mace are too short), 296: (?<! [aciozj] ) # the last of them not one of a c i o z j, 297: \b # and the word ends there 298: | \b Mc # or "Mc" at the start of a word 299: }x; 300: 301: Readonly my @POST_NOMINAL_INITIALS => qw( 302: VC GC KG LG KT LT KP GCB OM GCSI GCMG GCIE GCVO GBE CH KCB DCB KCSI KCMG 303: DCMG KCIE KCVO DCVO KBE DBE CB CSI CMG CIE CVO CBE DSO LVO OBE ISO MVO MBE 304: IOM CGC RRC DSC MC DFC AFC ARRC OBI DCM CGM GM IDSM DSM MM DFM AFM SGM IOM 305: CPM QGM RVM BEM QPM QFSM QAM CPM MSM ERD VD TD UD ED RD VRD AE 306: 307: PC ADC QHP QHS QHDS QHNS QHC SCJ J LJ QS SL QC KC JP DL MP MSP MSYP AM AM 308: MLA MEP DBEnv DConstMgt DREst EdD DPhil PhD DLitt DSocSci MD EngD DD LLD 309: DProf MA MArch MAnth MSc MMORSE MMath MMathStat MPharm MPhil MSc MSci MSt 310: MRes MEng MChem MBiochem MSocSc MMus LLM BCL MPhys MComp MAcc MFin MBA MPA 311: MEd MEP MEnt MCGI MGeol MLitt MEarthSc MClinRes BA BSc LLB BEng MBChB FdA 312: FdSc FdEng PgDip PgD PgCert PgC PgCLTHE AUH AKC AUS HNC HNCert HND HNDip 313: DipHE Dip OND CertHE ACSM MCSM DIC AICSM ARSM ARCS LLB LLM BCL MJur DPhil 314: PhD LLD DipLP FCILEx GCILEx ACILEx CQSW DipSW BSW MSW FCILT CMILT MILT CPL 315: CTP CML PLS CTL DLP PLog EJLog ESLog EMLog JrLog Log SrLog BArch MArch ARB 316: RIBA RIAS RIAI RSAW MB BM BS BCh BChir MRCS FRCS MS MCh. MRCP FRCP MRCPCH 317: FRCPCH MRCPath MFPM FFPM BDS MRCPsych FRCPsych MRCOG FRCOG MCEM FCEM FRCA 318: FFPMRCA MRCGP FRCGP BSc MScChiro MChiro MSc DC LFHOM MFHOM FFHOM FADO FBDO 319: FCOptom MCOptom MOst DPT MCSP FCSP. SROT MSCR FSCR. CPhT RN VN RVN BVSc 320: BVetMed VetMB BVM&S MRCVS FRCVS FAWM PGCAP PGCHE PGCE PGDE BEd NPQH QTS 321: CSci CSciTeach RSci RSciTech CEng IEng EngTech ICTTech DEM MM CMarEng 322: CMarSci CMarTech IMarEng MarEngTech RGN SRN RMN RSCN SEN EN RNMH RN RM RN1 323: RNA RN2 RN3 RNMH RN4 RN5 RNLD RN6 RN8 RNC RN7 RN9 RHV RSN ROH RFHN SPAN 324: SPMH SPCN SPLD SPHP SCHM SCLD SPCC SPDN V100 V200 V300 LPE MSc 325: ); 326: 327: # Built once at load time. Matching one alternation against the end of the 328: # name is far cheaper than the old loop of ~600 regex compilations per call. 329: # Later entries win a case-insensitive tie, as in the sequential original. 330: my %POST_NOMINAL_CANONICAL; 331: $POST_NOMINAL_CANONICAL{ lc $_ } = $_ for @POST_NOMINAL_INITIALS; 332: 333: # Finding a post-nominal "at the end" by scanning every word boundary costs time 334: # in proportion to the length of the name. Instead the name is reversed and the 335: # reversed entries are matched at the start, which takes the same time however 336: # long the name is. The entry must begin at a word boundary, so the character 337: # after it (in the reversed text) must not be a word character; every entry 338: # starts with a letter or digit, which makes that equivalent to the old \b. 339: my $POST_NOMINAL_REVERSED = do { 340: # Longest first, so the longest entry that fits wins, as before. 341: my $alternation = join '|', 342: map { quotemeta scalar reverse $_ } sort { length($b) <=> length($a) } keys %POST_NOMINAL_CANONICAL; 343: qr{ 344: \A \n? # an optional newline that ended the name 345: ($alternation) # an entry (reversed), captured 346: (?!\w) # not preceded (in the original) by a word character 347: }xi; 348: }; 349: 350: # How much of the end of a name can matter: the longest entry, a final newline 351: # and the character in front of the entry. Only this much is copied and 352: # reversed, so a huge name costs no more here than a short one. 353: my $POST_NOMINAL_WINDOW = 2 + max map { length } @POST_NOMINAL_INITIALS; 354: 355: #-------------------------------------------------------------------------- 356: # Public functions 357: 358: =head1 COMMON PITFALLS 359: 360: =over 4 361: 362: =item * A scalar is never changed in place 363: 364: C<NameCase(\$name)> and C<nc(\$name)> read the string and return a new 365: one. Always use the return value: C<$name = nc($name);>. 366: Only an I<array reference> is changed in place. 367: 368: =item * Empty and undefined input 369: 370: C<undef>, an empty string and the string "0" are returned as they are. 371: No warning is given. Check for C<undef> yourself if you need to know. 372: 373: =item * Switches are global 374: 375: The four switches are package variables. If you change one, it changes for 376: the whole program until you change it back. Use C<local> inside a block 377: to limit the change. 378: 379: =item * Only the last word can be a post-nominal 380: 381: "JANE PHD SMITH" is not changed to "Jane PhD Smith". "SMITH PHD" is 382: changed to "Smith PhD". 383: 384: =item * One name per string, with no extra text 385: 386: "MR. AND MRS. SMITH" and similar text get the same treatment as a name. 387: Words like "Of" are not changed to "of". 388: 389: =item * The result is a guess 390: 391: Some names are cased wrongly. For example "MACINNES" becomes "Macinnes". 392: Check important data by hand. See L</LIMITATIONS>. 393: 394: =item * Wrong number of arguments 395: 396: C<nc> takes at most one argument. C<NameCase> in scalar context takes 397: exactly one. Anything else stops the program with an error message, 398: so wrap the call in C<eval> if the input is not trusted. 399: 400: =item * Untrusted input 401: 402: Set C<$Lingua::EN::NameCase::MAX_LENGTH> when names come from users. Without 403: it, a very large string is processed in full, using memory in proportion to 404: its size. A class name in an error message is shortened and any odd 405: character in it becomes "?". 406: 407: =item * C<nc()> with no argument uses C<$_> 408: 409: This is the same as the built-in C<lc>. It can surprise you inside a loop. 410: 411: =back 412: 413: =head1 ENCODING 414: 415: The module works on Perl character strings. Decode your input first, 416: for example with C<Encode::decode('UTF-8', $bytes)> or by reading a file 417: with C<< open(my $fh, '<:encoding(UTF-8)', $file) >>. Print the result 418: through an encoded handle, for example C<< binmode(STDOUT, ':encoding(UTF-8)') >>. 419: 420: =over 4 421: 422: =item * Safe (decoded characters) 423: 424: Accented letters ("EMILE ZOLA" with an accent), Greek and other alphabets 425: that have upper and lower case, and emojis. An emoji is left as it is, 426: and the words around it are fixed: C<john E<lt>emojiE<gt> smith> becomes 427: C<John E<lt>emojiE<gt> Smith>. 428: 429: =item * Not safe (raw bytes) 430: 431: A UTF-8 byte string that was not decoded. The ASCII letters are fixed, but 432: the bytes of non-ASCII letters are left alone and are not changed to 433: capitals. 434: 435: =item * Scripts without case 436: 437: Chinese, Japanese, Korean, Arabic, Hebrew and similar text is returned 438: unchanged. It is safe to pass in. 439: 440: =item * Apostrophes 441: 442: Only the plain apostrophe (C<'>) is understood in the 's rule. 443: "FRED'S" becomes "Fred's", but "FRED" followed by a curly apostrophe and "S" 444: becomes "Fred" followed by the curly apostrophe and a capital "S". 445: 446: =item * Sharp s 447: 448: The German sharp s at the start of a word becomes "Ss". 449: 450: =item * Error messages 451: 452: The built-in messages are plain ASCII English. Text you put in 453: C<%MESSAGES> may be any characters; use character strings. 454: 455: =back 456: 457: The module ignores the process locale (C<LC_ALL>, C<LC_CTYPE>): the result 458: is the same everywhere. 459: 460: =head1 FUNCTIONS 461: 462: =head2 NameCase 463: 464: Takes a scalar, scalarref, array or arrayref, and changes the case of the 465: contents, as appropriate. Essentially a wrapper around nc(). 466: 467: =head3 PURPOSE 468: 469: Case one name, or a whole list of names, in one call. 470: 471: =head3 ARGS 472: 473: One scalar, one scalar reference, one array reference, or (in list context 474: only) a list of scalars. 475: 476: =head3 RETURNS 477: 478: =over 4 479: 480: =item * List context with a list, or an array reference 481: 482: A list of name-cased copies. The source is not modified. 483: 484: =item * Scalar or void context with an array reference 485: 486: The array is modified in place; the array reference is returned so calls 487: can be chained. The new names are stored into the existing elements, so a 488: reference to an element, or an array that aliases other variables (such as 489: C<\@_>), sees the change. 490: 491: =item * Scalar or scalar reference 492: 493: A name-cased copy. A scalar reference is I<not> modified (see L</LIMITATIONS>). 494: An undefined, empty or "0" value comes back unchanged. 495: 496: =back 497: 498: If the first argument is an array reference, any further arguments are 499: ignored. An empty array reference gives an empty list (or an unchanged 500: empty array). In list context a single scalar or scalar reference gives a 501: list of one name. 502: 503: =head3 SIDE EFFECTS 504: 505: Modifies the referenced array only in the in-place case above. If any 506: element is invalid, the function croaks and the array is left unchanged. 507: Dies (via L<Carp/croak>) on bad arguments. 508: 509: =head3 USAGE 510: 511: See L</SYNOPSIS>. 512: 513: =head3 EXAMPLE 514: 515: my @fixed = NameCase( 'JOHN SMITH', 'mary o\'neil' ); 516: # ('John Smith', "Mary O'Neil") 517: 518: my @names = ( 'ANNE JONES', 'BOB MCVEY' ); 519: NameCase( \@names ); 520: # @names is now ('Anne Jones', 'Bob McVey') 521: 522: my $one = NameCase( 'DAVID VAN DYKE' ); # 'David van Dyke' 523: 524: =head3 API SPECIFICATION 525: 526: =head4 input 527: 528: { 529: names => { 530: type => 'arrayref', # list of scalars, or one [] / \scalar 531: optional => 0, 532: min => 1, 533: }, 534: } 535: 536: A single hash reference, or any reference type other than SCALAR or ARRAY, 537: is rejected. 538: 539: Valid and invalid input, by partition: 540: 541: =over 4 542: 543: =item Argument form 544: 545: Valid: one string, one scalar reference (copied, not changed), one array 546: reference, or a list of strings. Invalid: no argument or, in scalar or 547: void context, more than one (croak C<single_arg>); a HASH, CODE, GLOB or 548: other reference (croak C<usage_namecase>). 549: 550: =item Array size 551: 552: 0, 1, 2 and many are all valid. An empty array returns an empty result. 553: In list context the original is never changed. In scalar or void context 554: an array reference is changed in place and returned. 555: 556: =item Each element 557: 558: Must satisfy the C<nc> domain (see below), including C<$MAX_LENGTH>. One 559: bad element croaks, and then no element of the array is changed. 560: 561: =back 562: 563: The domain of each element is the domain of L</nc>. 564: 565: =head4 output 566: 567: { type => 'arrayref', element_type => 'string' } # list context 568: { type => 'string' } # one scalar 569: { type => 'arrayref' } # in place 570: 571: =head3 MESSAGES 572: 573: =over 4 574: 575: =item C<usage_namecase> 576: 577: I<Usage: $SCALAR|@ARRAY = NameCase [\]$SCALAR|@ARRAY (got {got})>. 578: The first argument was a reference of an unsupported type (C<{got}>). 579: Pass a scalar, a scalar ref or an array ref. 580: 581: =item C<single_arg> 582: 583: I<NameCase only accepts a single scalar, array or array ref>. 584: No arguments were given, or several were given in scalar context. 585: Pass exactly one value, or call in list context. 586: 587: =back 588: 589: =head3 PSEUDOCODE 590: 591: validate: reject refs that are neither ARRAY nor SCALAR 592: if list context and (more than one arg or an ARRAY ref): 593: return nc of each element 594: elsif ARRAY ref: 595: replace each element by nc(element); return the ref 596: elsif SCALAR ref: 597: return nc(dereferenced value) 598: elsif exactly one arg: 599: return nc(arg) 600: else: 601: croak single_arg 602: 603: =cut 604: 605: sub NameCase { โ—606 โ†’ 612 โ†’ 622 606: my $first = $_[0]; 607: my $kind = ref $first; # '' for a plain scalar or no argument 608: 609: _fail( 'usage_namecase', { got => $kind } ) if $kind && !$ACCEPTED_REF{$kind}; 610: 611: # We have an array, or several scalars, in list context: return a list. 612: if ( wantarray && ( @_ > 1 || $kind eq 'ARRAY' ) ) {

Mutants (Total: 4, Killed: 4, Survived: 0)

613: return map { nc($_) } @{ $kind eq 'ARRAY' ? $first : \@_ };

Mutants (Total: 2, Killed: 2, Survived: 0)

614: } 615: 616: # An array ref in scalar/void context is converted in place, as that is 617: # the only way to be useful when no list is wanted. The whole answer is 618: # built first, so a bad element croaks before the caller's array is touched. 619: # It is then stored into the existing elements (a slice), not by replacing 620: # the array contents, so a caller's references to elements, and an array 621: # that aliases other variables (such as \@_), see the change. โ—622 โ†’ 622 โ†’ 629 622: if ( $kind eq 'ARRAY' ) {

Mutants (Total: 1, Killed: 1, Survived: 0)

623: my @fixed = map { nc($_) } @{$first}; 624: @{$first}[ 0 .. $#fixed ] = @fixed; 625: return $first;

Mutants (Total: 2, Killed: 2, Survived: 0)

626: } 627: 628: # Scalar refs are copied, not modified (documented limitation). 629: return nc( ${$first} ) if $kind eq 'SCALAR';

Mutants (Total: 2, Killed: 2, Survived: 0)

630: 631: _fail('single_arg') unless @_ == 1;

Mutants (Total: 1, Killed: 1, Survived: 0)

632: return nc($first);

Mutants (Total: 2, Killed: 2, Survived: 0)

633: } 634: 635: =head2 nc 636: 637: Takes a scalar or scalarref, and change the case of the name in the 638: corresponding string appropriately. 639: 640: =head3 PURPOSE 641: 642: Name-case a single string. 643: 644: =head3 ARGS 645: 646: Zero or one argument: a string or a scalar reference to a string. 647: With no argument, C<$_> is used (like C<lc> and C<uc>). 648: 649: =head3 RETURNS 650: 651: The name-cased string. An undefined, empty or "0" input is returned 652: unchanged. The input is never modified. 653: 654: =head3 SIDE EFFECTS 655: 656: None. Reads the package variables listed under L</CONFIGURATION>. 657: It does not change C<$_>, C<$@>, C<$!> or any C<alarm> timer. 658: 659: =head3 USAGE 660: 661: use Lingua::EN::NameCase qw(nc); 662: print nc('MR. JON WHITACRE III'); # Mr. Jon Whitacre III 663: 664: =head3 EXAMPLE 665: 666: nc('KEITH'); # 'Keith' 667: nc('o\'callaghan'); # "O'Callaghan" 668: nc('mccarthy'); # 'McCarthy' 669: nc(\ 'henry viii'); # 'Henry VIII' 670: nc('van der post'); # 'van der Post' 671: 672: local $Lingua::EN::NameCase::ROMAN = 0; 673: nc('na li'); # 'Na Li' 674: 675: =head3 API SPECIFICATION 676: 677: =head4 input 678: 679: { 680: name => { 681: type => 'string', # or a scalarref to a string 682: optional => 1, # defaults to $_ 683: max => undef, # $MAX_LENGTH, when set 684: }, 685: } 686: 687: Valid and invalid input, by partition: 688: 689: =over 4 690: 691: =item Argument count 692: 693: Valid: 0 (C<$_> is used) or 1. Invalid: 2 or more (croak C<usage_nc>, 694: reported as C<list>). 695: 696: =item Argument type 697: 698: Valid: a string, a number, a scalar reference, C<undef>, C<''> and C<'0'> 699: (the last three are returned unchanged). Invalid: any other reference 700: (HASH, ARRAY, CODE, GLOB, REF, Regexp, or an object); croak C<usage_nc>, 701: with the type or class name made safe and cut to 64 characters. 702: 703: =item Length (C<$MAX_LENGTH>) 704: 705: Counted in characters, never bytes. C<undef> means no limit. A length 706: equal to the maximum is accepted. One character more croaks C<too_long>. 707: A maximum of 0 admits only the false values. Negative or non-numeric 708: maximums are not checked; keep to non-negative integers. 709: 710: =item Text 711: 712: Any character string is accepted: ASCII, accented Latin, Greek, Cyrillic, 713: CJK, Hebrew, emoji, combining marks (Zalgo), and bidi controls such as 714: U+202E. None of these crash or lose characters. The result is at most 3 715: times as long as the input. Undecoded bytes are not cased. 716: 717: =item Recognised patterns 718: 719: C<Mac> is split when 3 or more letters follow and the last is not one of 720: C<a c i o z j>; C<Mc> is always split. Roman numerals I to LXXXIX are 721: converted; 90 (XC), IIII, XXXX and LXXXX are not. Post-nominals are 722: converted only at the end of the string. 723: 724: =back 725: 726: =head4 output 727: 728: { type => 'string', optional => 1 } # undef in, undef out 729: 730: =head3 MESSAGES 731: 732: =over 4 733: 734: =item C<usage_nc> 735: 736: I<Usage: nc [[\]$SCALAR] (got {got})>. 737: More than one argument, or a reference that is not a scalar reference, 738: was supplied (C<{got}> names the type). Pass one string or C<\$string>. 739: 740: =item C<too_long> 741: 742: I<Name is too long: {length} characters (the maximum is {max})>. 743: C<$MAX_LENGTH> is set and the name is longer. Shorten the input, or raise 744: the limit. 745: 746: =back 747: 748: =head3 PSEUDOCODE 749: 750: validate arguments (at most one; a plain scalar or SCALAR ref) 751: take the argument, or $_ when none was given 752: dereference it if it is a reference 753: return it at once if it is false (undef, '', '0') 754: lowercase it, capitalise each word, lowercase 's 755: apply the Mc/Mac rules 756: lowercase the particles (da, de, van, von, ...) 757: if ROMAN: upper-case roman numerals 758: if POSTNOMINAL: normalise a trailing PhD, MBE, ... 759: return the result 760: 761: =cut 762: 763: sub nc { 764: # Read the argument exactly once. A tied variable could answer differently 765: # each time it is read, which would let a bad value slip past the check. 766: # With no argument we work on $_, so the caller's $_ is never modified, 767: # even when it holds a reference. 768: my $name = @_ ? $_[0] : $_; 769: my $kind = ref $name; 770: 771: _fail( 'usage_nc', { got => $kind || 'list' } ) 772: if @_ > 1 || ( $kind && $kind ne 'SCALAR' );

Mutants (Total: 3, Killed: 3, Survived: 0)

773: 774: $name = ${$name} if $kind; 775: 776: # undef, '' and '0' have no case to fix. 777: return $name unless $name;

Mutants (Total: 2, Killed: 2, Survived: 0)

778: 779: # Refuse oversize input before any copy of it is made. 780: _fail( 'too_long', { length => length $name, max => $MAX_LENGTH } ) 781: if defined $MAX_LENGTH && length $name > $MAX_LENGTH;

Mutants (Total: 3, Killed: 3, Survived: 0)

782: 783: $name = _base_case($name); 784: $name = _mac_case($name); 785: $name = _particle_case($name); 786: $name = _roman_case($name) if $ROMAN; 787: $name = _postnominal_case($name) if $POSTNOMINAL; 788: 789: return $name;

Mutants (Total: 2, Killed: 2, Survived: 0)

790: } 791: 792: #-------------------------------------------------------------------------- 793: # Private functions (locked by Sub::Private when it is installed; see above). 794: 795: # Purpose: Raise a localised error. 796: # Entry: $key is a message id; $args is an optional hashref of 797: # placeholder values. 798: # Exit status: Never returns. 799: # Side effects: Croaks, reporting the error at the caller of the public 800: # function (Carp skips frames inside this package). 801: sub _fail { 802: my ( $key, $args ) = @_; 803: 804: # The type name may come from an attacker (a class name can hold newlines 805: # or be megabytes long), so it is made safe before it reaches a log. 806: $args = { %{ $args || {} } }; 807: $args->{got} = _safe_type( $args->{got} ) if defined $args->{got}; 808: 809: # An empty or missing text would make a useless error: fall back to the id. 810: my $message = _i18n( $key, $args ); 811: $message = $key unless defined $message && length $message; 812: croak $message; 813: 814: # Not reached: croak never returns. This stops a guard clause from 815: # falling through into bad data if croak is ever replaced. 816: # TODO: Unreachable code detected during path analysis. Investigate for removal. 817: die $message; ## no critic 818: } 819: 820: # Purpose: Make a reference type or class name safe to show in a message. 821: # Entry: $type is a string (possibly hostile). 822: # Exit status: Returns the string with every character other than a word 823: # character or colon replaced by "?", cut to a fixed length. 824: # Side effects: None. 825: sub _safe_type { 826: my ($type) = @_; 827: 828: # Cut first, then clean: a class name can be megabytes long. 829: $type = substr $type, 0, $MAX_TYPE_NAME_LENGTH; 830: $type =~ s{ [^\w:] }{?}gx; 831: 832: return $type;

Mutants (Total: 2, Killed: 2, Survived: 0)

833: } 834: 835: # Purpose: Turn a message id into text, in the user's wording if they 836: # have supplied one in %MESSAGES. 837: # Entry: $key is a message id; $args is an optional hashref. 838: # Each {name} in the template is replaced by $args->{name}; 839: # an unknown {name} is left as written. 840: # Exit status: Returns the message string; an unknown key is returned as is. 841: # Side effects: None. 842: sub _i18n { 843: my ( $key, $args ) = @_; 844: 845: # A missing key is a programming error, but it must not hide the real 846: # problem behind a second warning. 847: $key = 'unknown_message' unless defined $key; 848: $args ||= {}; 849: # Force a plain string: a reference here would become the exception itself. 850: my $template = '' . ( $MESSAGES{$key} // $DEFAULT_MESSAGES{$key} // $key ); 851: 852: $template =~ s{ \{ (\w++) \} }{ $args->{$1} // "{$1}" }gex; 853: 854: return $template;

Mutants (Total: 2, Killed: 2, Survived: 0)

855: } 856: 857: # Purpose: Lowercase everything, capitalise each word, then undo the 858: # capital after an apostrophe (O'Neil stays, but Fred's -> Fred's). 859: # Entry: $name is a non-empty string. 860: # Exit status: Returns the converted string. 861: # Side effects: None. 862: sub _base_case { 863: my ($name) = @_; 864: 865: $name = lc $name; 866: $name =~ s{ \b (\w) }{\u$1}gx; 867: $name =~ s{ (\'\w) \b }{\L$1}gx; 868: 869: return $name;

Mutants (Total: 2, Killed: 2, Survived: 0)

870: } 871: 872: # Purpose: Fix Mc and Mac names, e.g. McDonald, MacDonald, but Machado. 873: # Entry: $name has been through _base_case(). 874: # Exit status: Returns the converted string. 875: # Side effects: None. 876: sub _mac_case { โ—877 โ†’ 880 โ†’ 887 877: my ($name) = @_; 878: 879: # Taken from NameParse.pm: only touch names that look like Mc/Mac names. 880: if ( $name =~ $MAC_NAME ) {

Mutants (Total: 1, Killed: 1, Survived: 0)

881: $name =~ s{ \b (Ma?c) ([A-Za-z]) }{$1\u$2}gx; 882: 883: # Undo the capital for one-word exceptions such as Machado. 884: $name =~ s{$MAC_EXCEPTION}{Mac\l$1}g; 885: $name =~ s{ \b Macisaac }{MacIsaac}gx; 886: } 887: $name =~ s{ \b Macmurdo }{MacMurdo}gx; 888: 889: return $name;

Mutants (Total: 2, Killed: 2, Survived: 0)

890: } 891: 892: # Purpose: Lowercase "son of" particles: al, ap, da, de, del, van, von ... 893: # Entry: $name has been through _base_case(). 894: # Exit status: Returns the converted string. 895: # Side effects: None. 896: sub _particle_case { 897: my ($name) = @_; 898: 899: # Hebrew ben/bat need a preceding word, or "Ben Jones" would lose its 900: # capital: <http://www.jewfaq.org/jnames.htm>. El and La are lowercase in 901: # Greek and French, but not in Spanish. The pattern for the current 902: # switches was built at load time. 903: my $pattern = $PARTICLE_PATTERN{ ( $HEBREW ? 1 : 0 ) . ( $SPANISH ? 1 : 0 ) }; 904: $name =~ s{$pattern}{\l$1}g; 905: 906: return $name;

Mutants (Total: 2, Killed: 2, Survived: 0)

907: } 908: 909: # Purpose: Upper-case roman numerals, e.g. Henry VIII. 910: # Entry: $name has been through _base_case(). 911: # Exit status: Returns the converted string. 912: # Side effects: None. 913: sub _roman_case { 914: my ($name) = @_; 915: 916: $name =~ s{ \b ($ROMAN_NUMERAL) \b }{\U$1}gx; 917: 918: return $name;

Mutants (Total: 2, Killed: 2, Survived: 0)

919: } 920: 921: # Purpose: Put a trailing post-nominal (PhD, MBE ...) into its usual case. 922: # Entry: $name has been through _base_case(). 923: # Exit status: Returns the converted string. 924: # Side effects: None. 925: sub _postnominal_case { โ—926 โ†’ 932 โ†’ 944 926: my ($name) = @_; 927: 928: my $length = length $name; 929: my $tail = $length > $POST_NOMINAL_WINDOW ? substr( $name, $length - $POST_NOMINAL_WINDOW ) : $name;

Mutants (Total: 3, Killed: 3, Survived: 0)

930: my $reversed = reverse $tail; 931: 932: if ( $reversed =~ $POST_NOMINAL_REVERSED ) {

Mutants (Total: 1, Killed: 1, Survived: 0)

933: # Offsets are in the reversed tail, which ends where the name ends. 934: my ( $start, $end ) = ( $-[1], $+[1] ); 935: my $entry = lc scalar reverse substr( $reversed, $start, $end - $start ); 936: 937: # A text can match only through case folding (the long s U+017F matches 938: # "s", the "fi" ligature matches "fi") and then has no exact key. It is 939: # left as it is: writing the missing value would delete the text. 940: my $canonical = $POST_NOMINAL_CANONICAL{$entry}; 941: substr( $name, $length - $end, $end - $start ) = $canonical if defined $canonical; 942: } 943: 944: return $name;

Mutants (Total: 2, Killed: 2, Survived: 0)

945: } 946: 947: =head1 SECURITY 948: 949: The module only reads and builds strings. It opens no files, runs no 950: programs, uses no string C<eval>, and never turns its input into code or 951: into part of a regular expression. Notes for programs that use it: 952: 953: =over 4 954: 955: =item * Taint mode 956: 957: Taint is kept: a name that is tainted gives a tainted result. The module 958: never launders data and works under C<perl -T>. 959: 960: =item * Untrusted names 961: 962: Names from users can be very long. Set C<$Lingua::EN::NameCase::MAX_LENGTH>. 963: Case mapping can lengthen text: the result is at most three times as long as 964: the input. The length check is on the input, before the mapping. 965: 966: =item * Error messages 967: 968: The type or class name of a bad argument is cut to 64 characters and any 969: character other than a letter, digit, underscore or colon is shown as "?", 970: so a hostile class name cannot add lines or escape codes to a log. 971: 972: =item * Settings are global 973: 974: The switches, C<$MAX_LENGTH> and C<%MESSAGES> are package variables, so any 975: code in the same program can change them. Use C<local>. They are not a 976: security boundary. 977: 978: =item * Locked internals 979: 980: L<Sub::Private>, when installed, stops other packages calling the internal 981: routines. This is for tidiness, not security; it is switched off when the 982: environment variable C<HARNESS_ACTIVE> is true, and it is absent when 983: L<Sub::Private> is not installed. 984: 985: =item * Malformed text 986: 987: Invalid characters (lone surrogates, code points above U+10FFFF) are passed 988: through without a warning. Check the encoding of untrusted input before 989: calling this module. 990: 991: =back 992: 993: =head1 PERFORMANCE 994: 995: A typical name (two to four words) takes about 10 microseconds, which is 996: about 100,000 names a second, measured on an ordinary desktop with Perl 5.40. 997: The time grows in step with the length of the name. Each step is a small 998: number of regular expression passes over the name, and 999: the cost of each pass was measured and tuned: 1000: 1001: =over 4 1002: 1003: =item * The roman numeral and particle rules each make one pass. 1004: 1005: =item * A trailing post-nominal is found by matching the reversed name at its 1006: start, so a very long name costs no more for this step than a short one. 1007: 1008: =item * Patterns are compiled once, when the module loads. 1009: 1010: =item * If L<Sub::Private> is installed each internal call is about 0.4 1011: microseconds slower; this is the price of locking the internals. 1012: 1013: =back 1014: 1015: Set C<$Lingua::EN::NameCase::MAX_LENGTH> to bound the time spent on any one 1016: name. 1017: 1018: =head1 LIMITATIONS 1019: 1020: The design choices below are known weaknesses. 1021: 1022: =over 4 1023: 1024: =item * Global configuration 1025: 1026: C<$HEBREW>, C<$SPANISH>, C<$ROMAN> and C<$POSTNOMINAL> are package 1027: variables, so one part of a program changing them changes the result for 1028: all of it. Use C<local> to scope a change. A per-call options hash would 1029: be better, but would change the API. 1030: 1031: =item * Scalar references are not modified in place 1032: 1033: C<NameCase(\$name)> returns a copy. Changing this would break existing 1034: callers. 1035: 1036: =item * Exceptions are prefixes 1037: 1038: The "Mac" exceptions match the start of a word, so MacInnes becomes 1039: Macinnes and MacKenzie becomes Mackenzie. An exact-surname list would be 1040: more accurate but needs data this module does not have. 1041: 1042: =item * Everything is an English-language heuristic 1043: 1044: Names are not cased by a grammar. "Ben" and "Van" are lowercased only when 1045: they follow another word, and every word of a name is treated alike 1046: (C<Estate Of Laura Jones>). For real name parsing use 1047: L<Lingua::EN::NameParse>. 1048: 1049: =item * Locale is ignored 1050: 1051: Case rules are the Unicode rules, whatever the locale. Older versions used 1052: C<use locale>, which gave different answers on different machines. Data in 1053: a legacy 8-bit code page must be decoded first (see L</ENCODING>). Language 1054: rules are not applied, so Turkish "I" becomes "i", not a dotless "i". 1055: 1056: =item * The Mac test covers the whole string 1057: 1058: Whether the "Mac" rules apply is decided once for the whole string, not word 1059: by word. A string that holds both a name such as "Mcdonald" and a name such 1060: as "Macchiato" will have both treated as Mac names. Pass one name at a time. 1061: 1062: =item * Hebrew particles need one space 1063: 1064: "ben" and "bat" are recognised only when exactly one white space character 1065: separates them from the word in front. 1066: 1067: =item * Post-nominals only at the end 1068: 1069: Only the last word is checked, and the list is not exhaustive. 1070: Since the entries are now matched literally, "MCh." and "FCSP." require 1071: their final dot (the dot used to match any character). 1072: 1073: =item * Error messages 1074: 1075: Messages are English templates with C<{name}> placeholders, replaceable 1076: through C<%MESSAGES>. There is no plural or gender handling because none 1077: of the messages needs it. 1078: 1079: =item * Encapsulation 1080: 1081: The internal routines are guarded with L<Sub::Private> in enforce mode, but 1082: only if that module is installed. It is optional because it needs Perl 5.14 1083: or later and heavy dependencies; without it the internals are ordinary 1084: subroutines whose names start with an underscore. L<Sub::Protected> is not 1085: used because the module has no classes or methods to protect. 1086: 1087: =back 1088: 1089: =head1 BUGS 1090: 1091: The module covers the rules that I know of. There are probably a lot 1092: more rules, exceptions etc. for "Western"-style languages which could be 1093: incorporated. 1094: 1095: There are probably lots of exceptions and problems - but as a general 1096: data 'cleaner' it may be all you need. 1097: 1098: Use Kim Ryan's L<Lingua::EN::NameParse> for any really sophisticated name parsing. 1099: 1100: =head1 SEE ALSO 1101: 1102: =over 4 1103: 1104: =item * L<Test Dashboard|https://nigelhorne.github.io/Lingua-EN-NameCase/coverage/> 1105: 1106: =back 1107: 1108: =head1 SUPPORT 1109: 1110: You can find documentation for this module with the perldoc command. 1111: 1112: perldoc Lingua::EN::NameCase 1113: 1114: You can also look for information at: 1115: 1116: =over 4 1117: 1118: =item * MetaCPAN 1119: 1120: L<https://metacpan.org/release/Lingua-EN-NameCase> 1121: 1122: =item * RT: CPAN's request tracker 1123: 1124: L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=Lingua-EN-NameCase> 1125: 1126: =item * CPANTS 1127: 1128: L<http://cpants.cpanauthors.org/dist/Lingua-EN-NameCase> 1129: 1130: =item * CPAN Testers' Matrix 1131: 1132: L<http://matrix.cpantesters.org/?dist=Lingua-EN-NameCase> 1133: 1134: =item * CPAN Testers Dependencies 1135: 1136: L<http://deps.cpantesters.org/?module=Lingua::EN::NameCase> 1137: 1138: =back 1139: 1140: =head1 AUTHOR 1141: 1142: 1998-2014 Mark Summerfield <summer@qtrac.eu> 1143: 2014-present Barbie <barbie@cpan.org> 1144: 1145: 2020- Maintained by Nigel Horne, C<< <njh at nigelhorne.com> >> 1146: 1147: =head1 ACKNOWLEDGEMENTS 1148: 1149: Thanks to Kim Ryan <kimaryan@ozemail.com.au> for his Mc/Mac solution. 1150: 1151: =encoding utf8 1152: 1153: =head1 FORMAL SPECIFICATION 1154: 1155: This section is for readers who know Z notation. It is the only part of 1156: this file that is not plain ASCII. Each schema describes one function. 1157: A prime (') marks a value after the call. C<ARGS> is the list of arguments, 1158: C<ANY> is any Perl value, and C<STRING> is a Perl string. 1159: 1160: =head2 NameCase 1161: 1162: ┌─ NameCase ───────────────────────────────────────────── 1163: │ args? : seq ANY 1164: │ ctx? : { list, scalar, void } 1165: │ out! : seq STRING ∪ STRING ∪ ARRAYREF 1166: ├──────────────────────────────────────────────────────── 1167: │ ref(head args?) ∉ { ARRAY, SCALAR, ∅ } ⇒ croak usage_namecase 1168: │ ctx? = list ∧ (#args? > 1 ∨ ref(head args?) = ARRAY) 1169: │ ⇒ out! = nc ∘ (elements args?) 1170: │ ctx? ≠ list ∧ ref(head args?) = ARRAY 1171: │ ⇒ head args? ' = nc ∘ (head args?) ∧ out! = head args? 1172: │ ref(head args?) = SCALAR ⇒ out! = nc(↑(head args?)) 1173: │ ref(head args?) = ∅ ∧ #args? = 1 ⇒ out! = nc(head args?) 1174: │ otherwise ⇒ croak single_arg 1175: └──────────────────────────────────────────────────────── 1176: 1177: =head2 nc 1178: 1179: ┌─ nc ─────────────────────────────────────────────────── 1180: │ name? : STRING ∪ ↑STRING ∪ {⊥} 1181: │ out! : STRING ∪ {⊥} 1182: ├──────────────────────────────────────────────────────── 1183: │ #args > 1 ∨ ref(name?) ∉ { ∅, SCALAR } ⇒ croak usage_nc 1184: │ MAX_LENGTH ≠ ⊥ ∧ value ∉ {⊥, "", "0"} ∧ #value > MAX_LENGTH ⇒ croak too_long 1185: │ value = (name? ∈ ↑STRING ⇒ ↑name? ∨ name?) 1186: │ value ∈ {⊥, "", "0"} ⇒ out! = value 1187: │ otherwise 1188: │ out! = postnominal ∘ roman ∘ particles ∘ mac ∘ base (value) 1189: │ where roman and postnominal apply only when enabled 1190: └──────────────────────────────────────────────────────── 1191: 1192: =head2 Configuration 1193: 1194: ┌─ Config ─────────────────────────────────────────────── 1195: │ HEBREW, SPANISH, ROMAN, POSTNOMINAL : { 0, 1 } 1196: │ MAX_LENGTH : ℕ ∪ {⊥} 1197: │ MESSAGES : KEY ⇸ STRING 1198: └──────────────────────────────────────────────────────── 1199: ┌─ Init ───────────────────────────────────────────────── 1200: │ Config' 1201: ├──────────────────────────────────────────────────────── 1202: │ HEBREW' = 1 ∧ SPANISH' = 0 ∧ ROMAN' = 1 ∧ POSTNOMINAL' = 1 1203: │ MESSAGES' = ∅ ∧ MAX_LENGTH' = ⊥ 1204: └──────────────────────────────────────────────────────── 1205: ┌─ Set ────────────────────────────────────────────────── 1206: │ ΔConfig ; flag? : { HEBREW, SPANISH, ROMAN, POSTNOMINAL } ; v? : { 0, 1 } 1207: ├──────────────────────────────────────────────────────── 1208: │ flag?' = v? ∧ all other variables are unchanged 1209: └──────────────────────────────────────────────────────── 1210: 1211: nc and NameCase read Config and never change it (ΞConfig). 1212: 1213: =head1 STATE DIAGRAM 1214: 1215: The module keeps no data between calls except the configuration. So there 1216: are two small machines: the configuration, and what happens during one call. 1217: 1218: Configuration (the four switches, C<$MAX_LENGTH> and C<%MESSAGES>): 1219: 1220: use Lingua::EN::NameCase 1221: | 1222: v 1223: +-----------------+ set a switch or %MESSAGES key +-----------------+ 1224: | DEFAULTS |---------------------------------->| CUSTOMISED | 1225: | HEBREW=1 | action: later calls use it | any switch or | 1226: | SPANISH=0 |<----------------------------------| message differs | 1227: | ROMAN=1 | set back, or leave a block +-----------------+ 1228: | POSTNOMINAL=1 | that used "local" | ^ 1229: +-----------------+ +----------+ 1230: set again 1231: 1232: DEFAULTS also means that C<$MAX_LENGTH> is C<undef> and C<%MESSAGES> is 1233: empty. Both states accept every call below. Calls never change the 1234: configuration. 1235: 1236: One call to C<nc> or C<NameCase>: 1237: 1238: nc(...) / NameCase(...) 1239: | 1240: v 1241: +------------+ bad type, wrong count +----------+ 1242: | VALIDATING |------------------------->| FAILED | 1243: +------------+ action: croak with the +----------+ 1244: | message (usage_nc, (the caller 1245: | ok usage_namecase, gets an 1246: v single_arg) exception) 1247: +------------+ undef, "" or "0" +----------+ 1248: | READING |------------------------->| DONE | 1249: +------------+ action: return it as is +----------+ 1250: | ^ 1251: | has text | 1252: v | 1253: +------------+ base case, Mc/Mac, particles, | 1254: | CASING | roman numerals (if ROMAN), | 1255: +------------+ post-nominal (if POSTNOMINAL) | 1256: | | 1257: +---------------------------------------+ 1258: action: return the new string 1259: 1260: READING also goes to FAILED when $MAX_LENGTH is set and the text is 1261: longer (message too_long). The caller gets an exception and nothing 1262: is changed. 1263: 1264: NameCase only: an array ref in scalar or void context goes from 1265: CASING to DONE after replacing each element (the only side effect 1266: on caller data), and returns the array ref. 1267: 1268: =head1 LICENSE AND COPYRIGHT 1269: 1270: Copyright (c) Mark Summerfield 1998-2014. All Rights Reserved. 1271: Copyright (c) Barbie 2014-2015. All Rights Reserved. 1272: Copyright (c) Nigel Horne 2020-2026. All Rights Reserved. 1273: 1274: This distribution is free software; you can redistribute it and/or 1275: modify it under the Artistic License 2.0. 1276: 1277: =cut 1278: 1279: 1;