Name

Lingua::EN::NameCase - Correctly case a person's name from UPPERCASE or lowercase

Version

Version 1.22

Synopsis

    use Lingua::EN::NameCase qw( nc NameCase );

    # Pattern 1: fix one name.  nc() is like lc() and uc().
    my $name = nc('JOHN O\'CALLAGHAN');     # "John O'Callaghan"
    my $same = nc( \$name );                # a reference works too
                                            # ($name itself is not changed)

    # Pattern 2: fix a list of names.  You get a new list back.
    my @clean = NameCase( 'ANNE JONES', 'BOB MCVEY' );

    # Pattern 3: fix an array in place.
    my @names = ( 'ANNE JONES', 'BOB MCVEY' );
    NameCase( \@names );                    # @names is now fixed

    # Pattern 4: clean data read from a file or database.
    open( my $fh, '<:encoding(UTF-8)', 'names.txt' );
    while ( my $line = <$fh> ) {
            chomp $line;
            print nc($line), "\n";
    }

    # Pattern 5: change the rules for part of your program only.
    {
            local $Lingua::EN::NameCase::SPANISH = 1;   # keep "El" and "La"
            print nc('EL PASO');                        # "El Paso"
    }
    print nc('EL PASO');                            # "el Paso"

    # Pattern 6: catch bad input.
    eval { nc( { not => 'a name' } ) };
    print "Problem: $@" if $@;

    # Other switches (all are package variables):
    #   $Lingua::EN::NameCase::HEBREW      = 0;  # "Ben" stays "Ben"
    #   $Lingua::EN::NameCase::ROMAN       = 0;  # "Li" stays "Li", not "LI"
    #   $Lingua::EN::NameCase::POSTNOMINAL = 0;  # "PHD" becomes "Phd"

Description

Forenames and surnames are often stored either wholly in UPPERCASE or wholly in lowercase. This module allows you to convert names into the correct case where possible.

Although forenames and surnames are normally stored separately if they do appear in a single string, whitespace separated, NameCase and nc deal correctly with them.

NameCase currently correctly name cases names which include any of the following:

    Mc, Mac, al, el, ap, da, de, delle, della, di, du, del, der,
    la, le, lo, van and von.

It correctly deals with names which contain apostrophes and hyphens too.

Example Fixes

    Original            Name Case
    --------            ---------
    KEITH               Keith
    LEIGH-WILLIAMS      Leigh-Williams
    MCCARTHY            McCarthy
    O'CALLAGHAN         O'Callaghan
    ST. JOHN            St. John

plus "son (daughter) of" etc. in various languages, e.g.:

    VON STREIT          von Streit
    VAN DYKE            van Dyke
    AP LLWYD DAFYDD     ap Llwyd Dafydd
    etc.

plus names with roman numerals (up to 89, LXXXIX), e.g.:

    henry viii          Henry VIII
    louis xiv           Louis XIV

Configuration

The behaviour is controlled by package variables, read on every call so they may be changed at any time:

Common Pitfalls

Encoding

The module works on Perl character strings. Decode your input first, for example with Encode::decode('UTF-8', $bytes) or by reading a file with open(my $fh, '<:encoding(UTF-8)', $file). Print the result through an encoded handle, for example binmode(STDOUT, ':encoding(UTF-8)').

The module ignores the process locale (LC_ALL, LC_CTYPE): the result is the same everywhere.

Functions

NameCase

Takes a scalar, scalarref, array or arrayref, and changes the case of the contents, as appropriate. Essentially a wrapper around nc().

Purpose

Case one name, or a whole list of names, in one call.

Args

One scalar, one scalar reference, one array reference, or (in list context only) a list of scalars.

Returns

If the first argument is an array reference, any further arguments are ignored. An empty array reference gives an empty list (or an unchanged empty array). In list context a single scalar or scalar reference gives a list of one name.

Side Effects

Modifies the referenced array only in the in-place case above. If any element is invalid, the function croaks and the array is left unchanged. Dies (via "croak" in Carp) on bad arguments.

Usage

See "SYNOPSIS".

Example

    my @fixed = NameCase( 'JOHN SMITH', 'mary o\'neil' );
    # ('John Smith', "Mary O'Neil")

    my @names = ( 'ANNE JONES', 'BOB MCVEY' );
    NameCase( \@names );
    # @names is now ('Anne Jones', 'Bob McVey')

    my $one = NameCase( 'DAVID VAN DYKE' );   # 'David van Dyke'

Api Specification

Input
    {
            names => {
                    type     => 'arrayref',    # list of scalars, or one [] / \scalar
                    optional => 0,
                    min      => 1,
            },
    }

A single hash reference, or any reference type other than SCALAR or ARRAY, is rejected.

Valid and invalid input, by partition:

The domain of each element is the domain of "nc".

Output
    { type => 'arrayref', element_type => 'string' }    # list context
    { type => 'string' }                                # one scalar
    { type => 'arrayref' }                              # in place

Messages

Pseudocode

    validate: reject refs that are neither ARRAY nor SCALAR
    if list context and (more than one arg or an ARRAY ref):
            return nc of each element
    elsif ARRAY ref:
            replace each element by nc(element); return the ref
    elsif SCALAR ref:
            return nc(dereferenced value)
    elsif exactly one arg:
            return nc(arg)
    else:
            croak single_arg

Nc

Takes a scalar or scalarref, and change the case of the name in the corresponding string appropriately.

Purpose

Name-case a single string.

Args

Zero or one argument: a string or a scalar reference to a string. With no argument, $_ is used (like lc and uc).

Returns

The name-cased string. An undefined, empty or "0" input is returned unchanged. The input is never modified.

Side Effects

None. Reads the package variables listed under "CONFIGURATION". It does not change $_, $@, $! or any alarm timer.

Usage

    use Lingua::EN::NameCase qw(nc);
    print nc('MR. JON WHITACRE III');    # Mr. Jon Whitacre III

Example

    nc('KEITH');              # 'Keith'
    nc('o\'callaghan');       # "O'Callaghan"
    nc('mccarthy');           # 'McCarthy'
    nc(\ 'henry viii');       # 'Henry VIII'
    nc('van der post');       # 'van der Post'

    local $Lingua::EN::NameCase::ROMAN = 0;
    nc('na li');              # 'Na Li'

Api Specification

Input
    {
            name => {
                    type     => 'string',     # or a scalarref to a string
                    optional => 1,            # defaults to $_
                    max      => undef,        # $MAX_LENGTH, when set
            },
    }

Valid and invalid input, by partition:

Output
    { type => 'string', optional => 1 }    # undef in, undef out

Messages

Pseudocode

    validate arguments (at most one; a plain scalar or SCALAR ref)
    take the argument, or $_ when none was given
    dereference it if it is a reference
    return it at once if it is false (undef, '', '0')
    lowercase it, capitalise each word, lowercase 's
    apply the Mc/Mac rules
    lowercase the particles (da, de, van, von, ...)
    if ROMAN: upper-case roman numerals
    if POSTNOMINAL: normalise a trailing PhD, MBE, ...
    return the result

Security

The module only reads and builds strings. It opens no files, runs no programs, uses no string eval, and never turns its input into code or into part of a regular expression. Notes for programs that use it:

Performance

A typical name (two to four words) takes about 10 microseconds, which is about 100,000 names a second, measured on an ordinary desktop with Perl 5.40. The time grows in step with the length of the name. Each step is a small number of regular expression passes over the name, and the cost of each pass was measured and tuned:

Set $Lingua::EN::NameCase::MAX_LENGTH to bound the time spent on any one name.

Limitations

The design choices below are known weaknesses.

Bugs

The module covers the rules that I know of. There are probably a lot more rules, exceptions etc. for "Western"-style languages which could be incorporated.

There are probably lots of exceptions and problems - but as a general data 'cleaner' it may be all you need.

Use Kim Ryan's Lingua::EN::NameParse for any really sophisticated name parsing.

See Also

Support

You can find documentation for this module with the perldoc command.

    perldoc Lingua::EN::NameCase

You can also look for information at:

Author

1998-2014    Mark Summerfield <summer@qtrac.eu>
2014-present Barbie <barbie@cpan.org>

2020- Maintained by Nigel Horne, C<< <njh at nigelhorne.com> >>

Acknowledgements

Thanks to Kim Ryan kimaryan@ozemail.com.au for his Mc/Mac solution.

Formal Specification

This section is for readers who know Z notation. It is the only part of this file that is not plain ASCII. Each schema describes one function. A prime (') marks a value after the call. ARGS is the list of arguments, ANY is any Perl value, and STRING is a Perl string.

NameCase

    ┌─ NameCase ─────────────────────────────────────────────
    │ args? : seq ANY
    │ ctx?  : { list, scalar, void }
    │ out!  : seq STRING ∪ STRING ∪ ARRAYREF
    ├────────────────────────────────────────────────────────
    │ ref(head args?) ∉ { ARRAY, SCALAR, ∅ } ⇒ croak usage_namecase
    │ ctx? = list ∧ (#args? > 1 ∨ ref(head args?) = ARRAY)
    │     ⇒ out! = nc ∘ (elements args?)
    │ ctx? ≠ list ∧ ref(head args?) = ARRAY
    │     ⇒ head args? ' = nc ∘ (head args?) ∧ out! = head args?
    │ ref(head args?) = SCALAR ⇒ out! = nc(↑(head args?))
    │ ref(head args?) = ∅ ∧ #args? = 1 ⇒ out! = nc(head args?)
    │ otherwise ⇒ croak single_arg
    └────────────────────────────────────────────────────────

Nc

    ┌─ nc ───────────────────────────────────────────────────
    │ name? : STRING ∪ ↑STRING ∪ {⊥}
    │ out!  : STRING ∪ {⊥}
    ├────────────────────────────────────────────────────────
    │ #args > 1 ∨ ref(name?) ∉ { ∅, SCALAR } ⇒ croak usage_nc
    │ MAX_LENGTH ≠ ⊥ ∧ value ∉ {⊥, "", "0"} ∧ #value > MAX_LENGTH ⇒ croak too_long
    │ value = (name? ∈ ↑STRING ⇒ ↑name?  ∨  name?)
    │ value ∈ {⊥, "", "0"} ⇒ out! = value
    │ otherwise
    │   out! = postnominal ∘ roman ∘ particles ∘ mac ∘ base (value)
    │   where roman and postnominal apply only when enabled
    └────────────────────────────────────────────────────────

Configuration

    ┌─ Config ───────────────────────────────────────────────
    │ HEBREW, SPANISH, ROMAN, POSTNOMINAL : { 0, 1 }
    │ MAX_LENGTH : ℕ ∪ {⊥}
    │ MESSAGES : KEY ⇸ STRING
    └────────────────────────────────────────────────────────
    ┌─ Init ─────────────────────────────────────────────────
    │ Config'
    ├────────────────────────────────────────────────────────
    │ HEBREW' = 1 ∧ SPANISH' = 0 ∧ ROMAN' = 1 ∧ POSTNOMINAL' = 1
    │ MESSAGES' = ∅ ∧ MAX_LENGTH' = ⊥
    └────────────────────────────────────────────────────────
    ┌─ Set ──────────────────────────────────────────────────
    │ ΔConfig ; flag? : { HEBREW, SPANISH, ROMAN, POSTNOMINAL } ; v? : { 0, 1 }
    ├────────────────────────────────────────────────────────
    │ flag?' = v? ∧ all other variables are unchanged
    └────────────────────────────────────────────────────────

nc and NameCase read Config and never change it (ΞConfig).

State Diagram

The module keeps no data between calls except the configuration. So there are two small machines: the configuration, and what happens during one call.

Configuration (the four switches, $MAX_LENGTH and %MESSAGES):

      use Lingua::EN::NameCase
                |
                v
       +-----------------+   set a switch or %MESSAGES key   +-----------------+
       |    DEFAULTS     |---------------------------------->|   CUSTOMISED    |
       | HEBREW=1        |   action: later calls use it      | any switch or   |
       | SPANISH=0       |<----------------------------------| message differs |
       | ROMAN=1         |   set back, or leave a block      +-----------------+
       | POSTNOMINAL=1   |   that used "local"                  |          ^
       +-----------------+                                      +----------+
                                                                set again

DEFAULTS also means that $MAX_LENGTH is undef and %MESSAGES is empty. Both states accept every call below. Calls never change the configuration.

One call to nc or NameCase:

     nc(...) / NameCase(...)
            |
            v
      +------------+  bad type, wrong count   +----------+
      | VALIDATING |------------------------->|  FAILED  |
      +------------+  action: croak with the  +----------+
            |         message (usage_nc,       (the caller
            | ok      usage_namecase,           gets an
            v         single_arg)               exception)
      +------------+  undef, "" or "0"        +----------+
      |  READING   |------------------------->|   DONE   |
      +------------+  action: return it as is +----------+
            |                                       ^
            | has text                              |
            v                                       |
      +------------+  base case, Mc/Mac, particles,  |
      |   CASING   |  roman numerals (if ROMAN),     |
      +------------+  post-nominal (if POSTNOMINAL)  |
            |                                       |
            +---------------------------------------+
              action: return the new string

      READING also goes to FAILED when $MAX_LENGTH is set and the text is
      longer (message too_long).  The caller gets an exception and nothing
      is changed.

      NameCase only: an array ref in scalar or void context goes from
      CASING to DONE after replacing each element (the only side effect
      on caller data), and returns the array ref.

Copyright (c) Mark Summerfield 1998-2014. All Rights Reserved. Copyright (c) Barbie 2014-2015. All Rights Reserved. Copyright (c) Nigel Horne 2020-2026. All Rights Reserved.

This distribution is free software; you can redistribute it and/or modify it under the Artistic License 2.0.