in reply to Parsing out first names

I wouldn't use a regex (well sorta). I'd use a split on whitespace. This also makes it easy to get last names by popping off the last value.

Also watch your brackets. You want () for an array.

my @names = ( "Mark K.", "Bob H", "Kurt", "Mary Kay K", "Mary Jo Z.", "Mary Jo" ); foreach ( @names ) { my ($f_name) = (split)[0]; my ($l_name) = (split)[-1]; print "$f_name \n"; }


grep
One dead unjugged rabbit fish later

Replies are listed 'Best First'.
Re^2: Parsing out first names
by driver8 (Scribe) on Oct 13, 2006 at 07:17 UTC
    This is a good thought, but it only prints out:
    Mark Bob Kurt Mary Mary Mary
    which is only the first part of the first names--some of them are not complete.
      So do what grep already hinted at, split and keep only the parts you want:
      foreach ( @names ) { my @name_parts = split; pop @name_parts if $name_parts[-1] =~ /^[a-zA-Z]\.?$/; # throw last +name away my $f_name = join ' ', @name_parts; print "$f_name\n"; }

      Updated code to reflect Not_a_Number's correction, thanks!

      -- Hofmator

      Code written by Hofmator and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

        pop @name_parts; # throw last name away

        Look at the OP's list of names again: some of them are only first names. This code throws "Kurt" away completely, as well as "Jo" in the second "Mary Jo".

        Update: That line can be replaced by:

        pop @name_parts if $name_parts[-1] =~ /^[a-zA-Z]\.?$/;
        That works, but now you just have an obfuscated version of
        foreach my $name ( @names ) { $name =~ s/ [a-zA-Z]\.?$//; print "$name \n"; }