Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manipulating single and multiple word strings

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?

like image 726
yonetpkbji Avatar asked Apr 14 '26 04:04

yonetpkbji


2 Answers

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;
}
like image 133
RobEarl Avatar answered Apr 17 '26 13:04

RobEarl


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;
like image 33
fin Avatar answered Apr 17 '26 11:04

fin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!