htmanning has asked for the wisdom of the Perl Monks concerning the following question:

This my be simple but how do I strip the first name from a string if the string contains two names separated by a space.
$contact="Firstname Lastname";
I want to end up with
$contact = "Mr. Lastname";
And what about if someone has an initial in there like this:
$contact = "G. First Last";
I know how to strip out words I know, but going through a list of 10,000 names I have to somehow determine the names based on the space. Thanks.

Replies are listed 'Best First'.
Re: Strip first name from string
by toolic (Bishop) on Jan 29, 2014 at 00:52 UTC
    Use s/// to delete everything before the last name:
    use warnings; use strict; my $contact = "Firstname Lastname"; $contact =~ s/ .* \s (\S+) $ /Mr. $1/x; print "$contact\n";

    Or maybe Lingua::EN::NameParse

      Your regexp is too "expensive". You do not need capturing.

      Simply delete everything up to a whitespace:

      use warnings; use strict; my $contact = "Firstname Lastname"; $contact =~ s/^.*\s/Mr. /; print "$contact\n";

      s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
      +.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e
Re: Strip first name from string
by AnomalousMonk (Archbishop) on Jan 29, 2014 at 01:01 UTC

    The trouble with this sort of problem statement is that it is subject to all kinds of counter-exemplification: so, what about a name like "G. Gordon Liddy Sr., PhD"?

      Exactly. I don't know how to handle that, but I did do this and it worked okay:
      @contactname = split(' ',$contact); $firstname = $contactname[0]; $lastname = $contactname[1]; $showcontactname = "Mr. $lastname";

      While I agree with your statement that ..The trouble with this sort of problem statement is that it is subject to all kinds of counter-exemplification I will want to second toolic mention of Lingua::EN::NameParse.

      And for a one off name like you mentioned one could do this:

      print sprintf 'Mr. %3$s' => split/ / => "G. Gordon Liddy Sr., PhD"; #M +r. Liddy

      If you tell me, I'll forget.
      If you show me, I'll remember.
      if you involve me, I'll understand.
      --- Author unknown to me

        While I understand what the fat commas are doing in there (I think), it's more perplexing why you used print sprintf instead of just printf. What am I missing here?

Re: Strip first name from string (parse name first last stemming)
by Anonymous Monk on Jan 29, 2014 at 01:00 UTC
Re: Strip first name from string
by vinoth.ree (Monsignor) on Jan 29, 2014 at 07:13 UTC

    use warnings; use strict; my $contact = "Firstname Lastname"; #my $contact = "G. Lastname"; my ($Fname,$Lname) = split(' ',$contact); if($Fname =~ /.*\./ ) { print join (' ', ('Mr',$Fname,$Lname)); } else { print join (' ', ('Mr',$Lname)); }

    All is well

      /.*\./ is equivalent to /\./