I have an array containing a number of names:
Fred Smith
Dave Davidson
John
Andy Wood
Robin van Persie
foreach my $name ( @arrayOfNames ) {
my ($first, $last) = $name =~ /(.*)\s+(.).*/;
print "$first$last";
}
Using the foreach loop shown above it should print the following:
FredS
DavidD
John
AndyW
RobinvP
However, it does not handle one word names (John) or more than two word names (Robin van Persie) correctly:
For one word names (John) I get errors as shown below
Use of uninitialized value $first in concatenation...
Use of uninitialized value $last in concatenation...
And for more than two word names (Robin van Persie) it prints Robin vanP instead of RobinvP
How should it be changed to cater for these one word and more than two word names? Should one word and more than two word names be moved into a new array and then dealt with later on or can the regex be altered to cater for this?
You can use split instead of a regex to separate the first name from the other names:
my ($first, @rest) = split;
Then substr within map to extract the initials:
my @initials = map { substr $_, 0, 1 } @rest;
Then join them all together:
join '', $first, @initials;
Putting it all together:
for (@arrayOfNames) {
my ($first, @rest) = split;
print join '', $first, map { substr $_, 0, 1 } @rest;
}
I can't think of a way to do this easily with regex, but this works:
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my @names = ('Fred Smith', 'Dave Davidson', 'John', 'Andy Wood', 'Robin van Persie');
my @abbvr = map { my ($n, @n) = split;
$n .= substr($_, 0, 1) for @n;
$n } @names;
print Dumper @abbvr;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With