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

I have a variable that I need to take apart where I get the firstname in one variable and the lastname in another variable.
A delimeter will always seperate the firstname and lastname using ZZZ:
JoeZZZJones
I need the firstname: Joe
and lastname: Jones
Another example might be: MikeZZZEvans
I need the firstname: Mike
and lastname: Evans
Basically the names change in each variable but the delimeter will always be the same.

My below attempt doesnt fetch any data.
$firstname = s/[a-zA-Z][a-zA-Z]^z{3}?^[a-zA-Z]^/{$1}/e; $lastname = s/^[a-zA-Z]^ZZZ[a-zA-Z]/{$1}/e;
Please advise.

Replies are listed 'Best First'.
Re: Extract firstname and lastname from variable
by GrandFather (Saint) on Mar 01, 2010 at 02:22 UTC

    The problem with your regexes is that you use the start of string anchor ^ in the middle of the string where it can't possibly match. In fact split is likely to be a better tool for this exercise. Consider:

    use strict; use warnings; for my $name (qw'JoeZZZJones JoeZZZJosephZZZJones Bobbie') { my @parts = split 'ZZZ', $name; print "Name: $name\n"; print "Name part $_: $parts[$_ - 1]\n" for 1 .. @parts; print "\n"; }

    Prints:

    Name: JoeZZZJones Name part 1: Joe Name part 2: Jones Name: JoeZZZJosephZZZJones Name part 1: Joe Name part 2: Joseph Name part 3: Jones Name: Bobbie Name part 1: Bobbie

    True laziness is hard work
      split also has the advantage that if you hit someone with a middle name you'll get three items in your array.
      This one absolutely good:
      /^([A-Z][a-z]+)([A-Z]+)?([A-Z][a-z]+)?$/ # stored in $1, $2, $3
      it works with:
      FooBBBBar FooBar Foo
Re: Extract firstname and lastname from variable
by ww (Archbishop) on Mar 01, 2010 at 02:37 UTC
    ++ GrandFather

    But if your homework assignment requires classic use of a regex (as nit-pickingly distinguished from use of a 'pattern' in split), you might hand in something like this:

    #!/usr/bin/perl use strict; use warnings; # 825797 while ( my $line = <DATA> ) { if ($line =~ /([A-Za-z ]+?)ZZZ([-A-Za-z]+)/) { my $fname = $1; my $lname= $2; chomp $lname; print "$lname \t $fname\n"; } } __DATA__ MikeZZZJones JohnZZZDoe FredZZZDoe Jean PierreZZZMcCoy JaneZZZSmith-Barre

    Note, however, that this deals with complexities beyond those in your problem statement (names 4 and 5)... but ignores possibilities such as GrandFather's "Bobbie" -- ie, bad data, from the POV of your spec.

    And from these replies, you should be able to complete what appears to be part 2 of the same homework assignment.

    Update: Fixed unclosed code tag in para 2 and clarified whose homework.