in reply to RegExp, grabbing first name

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"; }

Replies are listed 'Best First'.
Re: OT: Test framework (Re: RegExp, grabbing first name)
by hippo (Archbishop) on Feb 27, 2016 at 09:53 UTC

    Nice work comparing these approaches (++).

    If anyone wants the hippo version to work even in the OP-unspecified case, all that is required is to change the return statment to

    return $fname || $sname;

    which completes the test set for that approach.

      Thanks, updated.

      The proper reason I wrote this (and why I marked it as OT) was to get acquainted with (and get used to) TDD, so I didn't look deeper into the solutions than was necessary to fit them in…

      BTW in my private copy, I have the test case from Re^2: RegExp, grabbing first name :-)
      'PEPPER ALICE BELINDA, CHARLOTTA, ..., YULIA, ZINNIA' => 'ALPHABET +'