I bloated up hippo's test Frame with the Solutions suggested so far and added some more test cases. They all do OK as far as specified and differ in the "unspecified by OP" cases:
#!/usr/bin/env perl use 5.011; # implies strict + feature 'say' use warnings; use Test::More; my %names = ( # Test data # input expected output 'BULLOCK JOE A' => 'JOE', 'SMITH, A DOE' => 'DOE', 'BULLOCK MICHAEL A' => 'MICHAEL', # not specified by OP: 'SMITH ADAM' => 'ADAM', 'POCAHONTAS' => 'POCAHONTAS', 'TRAPPER JOHN M D' => 'JOHN', ); my %approaches = ( 'hippo' => sub { my $fullname = shift; my ( $sname, $fname ) = $fullname =~ /([A-Z]{3,})/g; return $fname || $sname; # updated as per [id://1156306] }, 'Maresia' => sub { my $string = shift; if ( $string =~ /(\w{3,})$/ ) { return $1; } elsif ( $string =~ /(\w+)\s(\w{1,2})$/ ) { return $1; } }, 'kcott' => sub { shift =~ /^[^, ]+(?:,\s+\w+|)\s+(\w+)/; return $1; }, ); plan tests => scalar keys %approaches; for my $who ( keys %approaches ) { print "\nRunning tests for $who:\n\n"; subtest( $who, sub { plan tests => scalar keys %names; my $get_forename = $approaches{$who}; for my $fullname ( keys %names ) { my $fname = $get_forename->($fullname); no warnings 'uninitialized'; is( $fname, $names{$fullname}, "wanting forename '$names{$fullname}' from '$full +name'" ); } } ); print "\n"; }

In reply to OT: Test framework (Re: RegExp, grabbing first name) by soonix
in thread RegExp, grabbing first name by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.