blib/lib/Text/Names/Abbreviate.pm

filter: Statementstmt 100% 116 / 116 Branchbran 96.4% 54 / 56 Conditioncond 85.0% 34 / 40 MC/DCmcdc 66.6% 16 / 24 Subroutinesub 100% 13 / 13 Podpod 100% 1 / 1 totaltotal 93.6% 234 / 250 CC 43 SCAR 26.9
CC
43
Cov
96%
abbreviate
24.1
_extract_parts
11.0
_normalize_name
10.0
CRAP 14.7
↑ Summary
1 package Text::Names::Abbreviate;
2  
3 8 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 8 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 8 ▶use autodie qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
6 8 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 8 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 8 ▶use Exporter 'import';
Subroutine BEGIN: called CC=1 SCAR=0.0
10 8 ▶use Params::Get 0.13;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 8 ▶use Params::Validate::Strict 0.13;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 8 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 8 ▶use Unicode::Normalize ();
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 8 our @EXPORT_OK = qw(abbreviate);
16  
17 =head1 NAME
18  
19 Text::Names::Abbreviate - Create abbreviated name formats from full names
20  
21 =head2 VERSION
22  
23 Version 0.04
24  
25 =cut
26  
27 8 our $VERSION = '0.04';
28  
29 # ---------------------------------------------------------------------------
30 # Named constants -- eliminate magic strings throughout the logic
31 # ---------------------------------------------------------------------------
32 8 Readonly my $FMT_DEFAULT => 'default';
33 8 Readonly my $FMT_INITIALS => 'initials';
34 8 Readonly my $FMT_COMPACT => 'compact';
35 8 Readonly my $FMT_SHORTLAST => 'shortlast';
36 8 Readonly my $STY_FIRST => 'first_last';
37 8 Readonly my $STY_LAST => 'last_first';
38 8 Readonly my $DEFAULT_SEP => '.';
39  
40 # Common surname particles across Dutch, German, French, Italian, Spanish,
41 # Portuguese, Arabic, and Scandinavian naming traditions. Matching is
42 # case-sensitive: only lowercase tokens are eligible.
43 8 Readonly my @DEFAULT_PARTICLES => qw(
44 van de di da von der den des du
45 la le las los el al
46 te ten ter
47 af av
48 bin bint ibn
49 y do dos das del
50 zu zum zur
51 );
52  
53 # Single source of truth for parameter validation; also reflected in POD below.
54 8 Readonly my %PARAM_SCHEMA => (
55 name => {
56 type => 'string',
57 min => 1,
58 optional => 0,
59 },
60 format => {
61 type => 'string',
62 memberof => [ $FMT_DEFAULT, $FMT_INITIALS, $FMT_COMPACT, $FMT_SHORTLAST ],
63 optional => 1,
64 },
65 style => {
66 type => 'string',
67 memberof => [ $STY_FIRST, $STY_LAST ],
68 optional => 1,
69 },
70 separator => {
71 type => 'string',
72 optional => 1,
73 },
74 particles => {
75 type => ['boolean', 'arrayref'],
76 optional => 1,
77 },
78 );
79  
80 =head1 SYNOPSIS
81  
82 use Text::Names::Abbreviate qw(abbreviate);
83  
84 say abbreviate('John Quincy Adams'); # J. Q. Adams
85 say abbreviate('Adams, John Quincy'); # J. Q. Adams
86 say abbreviate('George R R Martin', { format => 'initials' }); # G.R.R.M.
87 say abbreviate('Ludwig van Beethoven'); # L. van Beethoven
88 say abbreviate("R\x{e9}mi Dupr\x{e9}"); # R. Dupr\x{e9}
89  
90 =head1 DESCRIPTION
91  
92 This module provides simple abbreviation logic for full personal names with
93 multiple formatting options and styles. Input is expected to be a personal
94 name consisting of one or more whitespace-separated components interpreted as:
95  
96 First [Middle ...] Last
97  
98 Names consisting of a single component are returned unchanged.
99  
100 =head1 SUBROUTINES/METHODS
101  
102 =head2 abbreviate
103  
104 Produce an abbreviated form of a personal name.
105  
106 =head3 Purpose
107  
108 Accept a full name in either C<First Middle Last> or C<Last, First Middle>
109 form and return a formatted abbreviated string according to the requested
110 C<format>, C<style>, C<separator>, and C<particles> options. Input is
111 NFC-normalised before processing, so strings differing only in Unicode
112 normalisation form produce identical output. Surname particles (C<van>,
113 C<de>, C<von>, etc.) are absorbed into the last-name component by default.
114  
115 =head3 Args
116  
117 =over 4
118  
119 =item name (required)
120  
121 Non-empty string. Accepted in two forms:
122  
123 =over 4
124  
125 =item C<First [Middle ...] Last>
126  
127 =item C<Last, First [Middle ...]>
128  
129 =back
130  
131 A leading comma (C<", John">) signals that no last name is present; only
132 initials are produced.
133  
134 =item format (optional, default C<default>)
135  
136 One of C<default>, C<initials>, C<compact>, C<shortlast>.
137  
138 =over 4
139  
140 =item C<default> -- C<J. Q. Adams>
141  
142 =item C<initials> -- C<J.Q.A.>
143  
144 =item C<compact> -- C<JQA>
145  
146 =item C<shortlast> -- initials then full last name; honours C<last_first> style
147 (e.g. C<Adams, J. Q.>).
148  
149 =back
150  
151 =item style (optional, default C<first_last>)
152  
153 One of C<first_last>, C<last_first>. All formats honour this option.
154  
155 =item separator (optional, default C<.>)
156  
157 String appended after each initial. Empty string removes all punctuation.
158  
159 =item particles (optional, default enabled)
160  
161 Controls detection of surname particles (C<van>, C<de>, C<von>, etc.) that
162 prefix the last name. Tokens immediately before the last name that appear in
163 the particle list are absorbed into the last-name component. Matching is
164 case-sensitive: only lowercase tokens are eligible.
165  
166 =over 4
167  
168 =item omitted or C<1> - use the built-in particle list
169  
170 =item C<0> - disable particle detection entirely
171  
172 =item arrayref of strings - use that list instead of the built-in one
173  
174 =back
175  
176 abbreviate('Ludwig van Beethoven'); # L. van Beethoven
177 abbreviate('Ludwig van Beethoven', { particles => 0 }); # L. v. Beethoven
178 abbreviate('Felipe de la Cruz', { particles => ['de','la'] }); # F. de la Cruz
179  
180 =back
181  
182 =head3 Returns
183  
184 A plain string. Returns C<''> for inputs that normalise to nothing (e.g. a
185 bare comma).
186  
187 =head3 Side Effects
188  
189 None. The function is purely functional with no persistent state.
190  
191 =head3 Usage
192  
193 # Positional
194 my $abbrev = abbreviate('John Quincy Adams');
195  
196 # Options hashref
197 my $abbrev = abbreviate('John Quincy Adams', {
198 format => 'initials',
199 style => 'last_first',
200 separator => '-',
201 });
202  
203 =head3 API SPECIFICATION
204  
205 INPUT
206 {
207 name => { type => 'string', min => 1, optional => 0 },
208 format => { type => 'string',
209 memberof => [qw(default initials compact shortlast)],
210 optional => 1 },
211 style => { type => 'string',
212 memberof => [qw(first_last last_first)],
213 optional => 1 },
214 separator => { type => 'string', optional => 1 },
215 particles => { type => ['boolean', 'arrayref'], optional => 1 },
216 }
217  
218 OUTPUT
219 { type => 'string' } # croaks on argument error
220  
221 =head3 MESSAGES
222  
223 Error Meaning / Resolution
224 --------------------------------------- -----------------------------------------------
225 name parameter missing or undefined Called without a name argument; supply one.
226 name must be a non-empty string Passed '' or undef; supply a non-empty string.
227 format must be one of: ... Invalid format constant; see API SPECIFICATION.
228 style must be one of: ... Invalid style constant; see API SPECIFICATION.
229 particles: must be one of boolean, Passed a string or hashref; pass 0/1 or an
230 arrayref arrayref of particle strings instead.
231  
232 =head3 PSEUDOCODE
233  
234 FUNCTION abbreviate(name, options):
235 Validate parameters via %PARAM_SCHEMA (croak on violation)
236 Assign defaults: format=default, style=first_last, sep=".", particles=built-in list
237 _normalize_name(name):
238 - NFC-normalize to precomposed Unicode form
239 - collapse consecutive commas
240 - detect and reorder "Last, First" form
241 - track $had_leading_comma (input had no last-name component)
242 - collapse internal whitespace; trim
243 Return '' if normalized name is empty
244 _extract_parts(name, had_leading_comma, format, style, particles):
245 - tokenize on whitespace
246 - pop last token as $last_name (unless leading-comma form)
247 - if particles enabled: while last remaining token is a particle,
248 pop it and prepend to $last_name
249 - build @initials from remaining tokens (first char each)
250 - if style=last_first and format!=default: unshift last initial, clear $last_name
251 - filter empty initials
252 Format result:
253 compact -> join('', @initials, first($last_name))
254 initials -> join($sep, @all_letters) . $sep
255 shortlast -> join(' ', map {"$_$sep"} @initials) . " $last_name"
256 default -> joined initials; prepend/append $last_name per $style
257  
258 =cut
259  
260 # ---------------------------------------------------------------------------
261 # Private helpers
262 # ---------------------------------------------------------------------------
263  
264 # Purpose: Resolve "Last, First" and leading-comma forms into a canonical
265 # "First ... Last" string, collapsing all internal whitespace.
266 # Entry Criteria: $raw is a defined, non-empty string (validated by the caller).
267 # Exit Status: Returns ($normalized, $had_leading_comma). $normalized is
268 # whitespace-collapsed and trimmed. $had_leading_comma is 1 when
269 # the original input began with a comma (no last-name component).
270 # Side Effects: None.
271 745 ▶sub _normalize_name {
Subroutine _normalize_name: called CC=10 SCAR=23.0
272 745 my ($raw) = @_;
273  
274 745 $raw = Unicode::Normalize::NFC($raw);
275 745 $raw =~ s/,+/,/g; # collapse any run of commas to one before splitting
276  
277 745 my $had_leading_comma = 0;
278  
279 745 ▶ if ($raw =~ /,/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($raw =~ /,/) 154 591 745
280 154 my ($last, $rest) = map { s/^\s+|\s+$//gr } split /\s*,\s*/, $raw, 2;
281 154 ▶ $rest //= q{};
Condition50%1/2
$rest //= ""
l!l
1540
MC/DC0%0/1
$rest //= ""
$rest
Truth table50%1/2
A
A= $rest
Aresult
11
00
282 154 ▶ $last //= q{};
Condition50%1/2
$last //= ""
l!l
1540
MC/DC0%0/1
$last //= ""
$last
Truth table50%1/2
A
A= $last
Aresult
11
00
283  
284 154 ▶ $had_leading_comma = 1 if !length($last) && length($rest);
Branch: 1 branch
BranchTrueFalseTotal
if not length $last and length $rest 74 80 154
Condition100%3/3
not length $last and length $rest
!ll&&!rl&&r
691174
MC/DC100%2/2
not length $last and length $rest
not length $last length $rest
Truth table100%3/3
not(A) and B
A= not length $lastB= length $rest
ABresult
0X0
100
111
285  
286 154 ▶ if (length($last) && length($rest)) {
Branch: 3 branches
BranchTrueFalseTotal
if (length $last and length $rest) { } 65 89 154
elsif (length $rest) { } 74 15 89
elsif (length $last) { } 4 11 15
Condition100%3/3
length $last and length $rest
!ll&&!rl&&r
85465
MC/DC100%2/2
length $last and length $rest
length $last length $rest
Truth table100%3/3
A and B
A= length $lastB= length $rest
ABresult
0X0
100
111
287 65 $raw = "$rest $last";
288 } elsif (length $rest) {
289 74 $raw = $rest;
290 } elsif (length $last) {
291 4 $raw = $last;
292 } else {
293 11 return (q{}, 0);
294 }
295 }
296  
297 734 $raw =~ s/^\s+|\s+$//g;
298 734 $raw =~ s/\s+/ /g;
299  
300 734 return ($raw, $had_leading_comma);
301 }
302  
303 # Purpose: Derive the ordered list of initials and the preserved last name
304 # from a normalized name string, honouring format, style, and particles.
305 # Entry Criteria: $name is output of _normalize_name (trimmed, single-spaced).
306 # $had_leading_comma is the boolean from _normalize_name.
307 # $format and $style are validated constants (FMT_*/STY_*).
308 # $particles is an arrayref of particle strings, or undef to disable.
309 # Exit Status: Returns ($initials_ref, $last_name). $initials_ref is an
310 # arrayref of single-character strings with empty entries removed.
311 # $last_name is '' when consumed by style/format reordering.
312 # Side Effects: None.
313 735 ▶sub _extract_parts {
Subroutine _extract_parts: called CC=11 SCAR=24.0
314 735 my ($name, $had_leading_comma, $format, $style, $particles) = @_;
315  
316 735 my @parts = split /\s+/, $name;
317 735 ▶ return ([], q{}) unless @parts;
Branch: 1 branch
BranchTrueFalseTotal
unless @parts 1 734 735
318  
319 734 my ($last_name, @initials);
320  
321 734 ▶ if ($had_leading_comma) {
Branch: 1 branch
BranchTrueFalseTotal
if ($had_leading_comma) { } 74 660 734
322 74 $last_name = q{};
323 74 @initials = map { substr $_, 0, 1 } @parts;
324 } else {
325 660 $last_name = pop @parts;
326  
327 # Absorb surname particles immediately preceding the last name.
328 660 ▶ if ($particles && @parts) {
Branch: 1 branch
BranchTrueFalseTotal
if ($particles and @parts) 512 148 660
Condition100%3/3
$particles and @parts
!ll&&!rl&&r
18130512
MC/DC100%2/2
$particles and @parts
$particles @parts
Truth table100%3/3
A and B
A= $particlesB= @parts
ABresult
0X0
100
111
329 512 my %is_particle = map { $_ => 1 } grep { defined } @{$particles};
330 512 ▶ while (@parts && $is_particle{ $parts[-1] }) {
Branch: 1 branch
BranchTrueFalseTotal
if (@parts and $is_particle{$parts[-1]}) 37 512 549
Condition66%2/3
@parts and $is_particle{$parts[-1]}
!ll&&!rl&&r
051237
MC/DC50%1/2
@parts and $is_particle{$parts[-1]}
@parts $is_particle{$parts[-1]}
Truth table66%2/3
A and B
A= @partsB= $is_particle{$parts[-1]}
ABresult
0X0
100
111
331 37 $last_name = (pop @parts) . q{ } . $last_name;
332 }
333 }
334  
335 660 @initials = map { substr $_, 0, 1 } @parts;
336  
337 # last_first on non-default formats (except shortlast, which keeps the full last name):
338 # move the last-name initial to the front and discard the full last name
339 660 ▶ if ($style eq $STY_LAST && $format ne $FMT_DEFAULT && $format ne $FMT_SHORTLAST && length $last_name) {
Branch: 1 branch
BranchTrueFalseTotal
if ($style eq $STY_LAST and $format ne $FMT_DEFAULT and $format ne $FMT_SHORTLAST and length $last_name) 61 599 660
Condition88%8/9
$style eq $STY_LAST and $format ne $FMT_DEFAULT and $format ne $FMT_SHORTLAST and length $last_name
!ll&&!rl&&r
599061
$style eq $STY_LAST and $format ne $FMT_DEFAULT and $format ne $FMT_SHORTLAST
!ll&&!rl&&r
5346561
$style eq $STY_LAST and $format ne $FMT_DEFAULT
!ll&&!rl&&r
46668126
MC/DC75%3/4
$style eq $STY_LAST and $format ne $FMT_DEFAULT and $format ne $FMT_SHORTLAST and length $last_name
$style eq $STY_LAST $format ne $FMT_DEFAULT $format ne $FMT_SHORTLAST length $last_name
Truth table80%4/5
A and B and C and D
A= $style eq $STY_LASTB= $format ne $FMT_DEFAULTC= $format ne $FMT_SHORTLASTD= length $last_name
ABCDresult
0XXX0
10XX0
110X0
11100
11111
340 61 unshift @initials, substr $last_name, 0, 1;
341 61 $last_name = q{};
342 }
343 }
344  
345 734 @initials = grep { length $_ } @initials;
346  
347 734 return (\@initials, $last_name);
348 }
349  
350 # ---------------------------------------------------------------------------
351 # Public API
352 # ---------------------------------------------------------------------------
353  
354 790 ▶sub abbreviate {
Subroutine abbreviate: called CC=24 SCAR=31.8
Pod documented
355 790 my $params = Params::Validate::Strict::validate_strict({
356 args => Params::Get::get_params('name', @_),
357 schema => \%PARAM_SCHEMA,
358 });
359  
360 Carp::croak(__PACKAGE__ . '::abbreviate: name parameter is required and must be defined')
361 737 ▶ unless defined $params->{name};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $params->{"name"} 0 737 737
362  
363 737 ▶ my $format = $params->{format} // $FMT_DEFAULT;
Condition66%2/3
$params->{"format"} // $FMT_DEFAULT
l!l&&r!l&&!r
4582790
MC/DC0%0/2
$params->{"format"} // $FMT_DEFAULT
$params->{"format"} $FMT_DEFAULT
Truth table66%2/3
A // B
A= $params->{"format"}B= $FMT_DEFAULT
ABresult
1X1
011
000
364 737 ▶ my $style = $params->{style} // $STY_FIRST;
Condition66%2/3
$params->{"style"} // $STY_FIRST
l!l&&r!l&&!r
3643730
MC/DC0%0/2
$params->{"style"} // $STY_FIRST
$params->{"style"} $STY_FIRST
Truth table66%2/3
A // B
A= $params->{"style"}B= $STY_FIRST
ABresult
1X1
011
000
365 737 ▶ my $sep = $params->{separator} // $DEFAULT_SEP;
Condition100%3/3
$params->{"separator"} // $DEFAULT_SEP
l!l&&r!l&&!r
2724578
MC/DC100%2/2
$params->{"separator"} // $DEFAULT_SEP
$params->{"separator"} $DEFAULT_SEP
Truth table100%3/3
A // B
A= $params->{"separator"}B= $DEFAULT_SEP
ABresult
1X1
011
000
366  
367 737 my $raw_particles = $params->{particles};
368 737 ▶ my $particles_ref =
Branch: 3 branches
BranchTrueFalseTotal
!defined($raw_particles) ? : 725 12 737
ref $raw_particles eq 'ARRAY' ? : 7 5 12
$raw_particles ? : 0 5 5
369 !defined $raw_particles ? \@DEFAULT_PARTICLES
370 : ref $raw_particles eq 'ARRAY' ? $raw_particles
371 : $raw_particles ? \@DEFAULT_PARTICLES
372 : undef;
373  
374 737 my ($name, $had_leading_comma) = _normalize_name($params->{name});
375 737 ▶ return q{} unless length $name;
Branch: 1 branch
BranchTrueFalseTotal
unless length $name 19 718 737
376  
377 718 my ($initials, $last_name) = _extract_parts($name, $had_leading_comma, $format, $style, $particles_ref);
378  
379 718 ▶ if ($format eq $FMT_COMPACT) {
Branch: 1 branch
BranchTrueFalseTotal
if ($format eq $FMT_COMPACT) 84 634 718
380 84 ▶ return join q{}, @{$initials},
Branch: 1 branch
BranchTrueFalseTotal
length $last_name ? : 48 35 83
381 (length $last_name ? (substr $last_name, 0, 1) : ());
382 }
383  
384 634 ▶ if ($format eq $FMT_INITIALS) {
Branch: 1 branch
BranchTrueFalseTotal
if ($format eq $FMT_INITIALS) 100 534 634
385 100 my @letters = @{$initials};
386 99 ▶ push @letters, substr($last_name, 0, 1) if length $last_name;
Branch: 1 branch
BranchTrueFalseTotal
if length $last_name 61 38 99
387 99 return join($sep, @letters) . $sep;
388 }
389  
390 534 ▶ if ($format eq $FMT_SHORTLAST) {
Branch: 1 branch
BranchTrueFalseTotal
if ($format eq $FMT_SHORTLAST) 159 375 534
391 159 ▶ my $joined = @{$initials} ? join(' ', map { $_ . $sep } @{$initials}) : q{};
Branch: 1 branch
BranchTrueFalseTotal
@{$initials;} ? : 113 46 159
392 159 ▶ if ($style eq $STY_LAST && length $last_name) {
Branch: 1 branch
BranchTrueFalseTotal
if ($style eq $STY_LAST and length $last_name) 64 95 159
Condition100%3/3
$style eq $STY_LAST and length $last_name
!ll&&!rl&&r
851064
MC/DC100%2/2
$style eq $STY_LAST and length $last_name
$style eq $STY_LAST length $last_name
Truth table100%3/3
A and B
A= $style eq $STY_LASTB= length $last_name
ABresult
0X0
100
111
393 64 ▶ return length($joined) ? "$last_name, $joined" : $last_name;
Branch: 1 branch
BranchTrueFalseTotal
length $joined ? : 43 21 64
394 }
395 95 ▶ return length($joined)
Branch: 2 branches
BranchTrueFalseTotal
length $joined ? : 70 25 95
length $last_name ? : 47 23 70
396 ? (length($last_name) ? "$joined $last_name" : $joined)
397 : $last_name;
398 }
399  
400 # default format
401 375 ▶ return $last_name unless @{$initials};
Branch: 1 branch
BranchTrueFalseTotal
unless @{$initials;} 68 307 375
402 307 my $joined = join ' ', map { $_ . $sep } @{$initials};
403 307 ▶ return ($style eq $STY_LAST && length $last_name)
Branch: 2 branches
BranchTrueFalseTotal
$style eq $STY_LAST && length $last_name ? : 47 260 307
length $last_name ? : 227 33 260
Condition100%3/3
$style eq $STY_LAST and length $last_name
!ll&&!rl&&r
252847
MC/DC100%2/2
$style eq $STY_LAST and length $last_name
$style eq $STY_LAST length $last_name
Truth table100%3/3
A and B
A= $style eq $STY_LASTB= length $last_name
ABresult
0X0
100
111
404 ? "$last_name, $joined"
405 : (length $last_name ? "$joined $last_name" : $joined);
406 }
407  
408 8 1;
409  
410 __END__
↑ Summary