Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

String operations

Status
Not open for further replies.

Helen79

Programmer
Dec 2, 2003
4
0
0
GB
Hello

I am trying to perform an operation on a string variable such as John,Leslie,Smith and get J.L.S. i.e. just the initials out.

This is driving me round the bend any help would be appreciated.

Many thanks

Helen
 
@names = (split /\,/, $string);

foreach $name (@names){
$firstInitial = substr($name,0,1);
.
.
.
}

 
Thanks for your reply hollywood. Is there a way of getting just a single string variable out instead of seperate ones?

Helen
 
I'm not sure exactly what you mean, but if you know what you are looking for in the string, completely or partially yes you can pull it out.
 
Thanks for your patience hollywood. Below i have show the value of the variable $forename before being shortened to just initials and the value of the variable $forename after being shortened.


John,Leslie --> J.L.
John --> J.
William,Carter,Smith --> W.C.S.

hope that helps
 
This will take the $forename value, and
create the $initials string. In the case, where

@names = (split /\,/, $forename);
$intials = "";
foreach $name (@names){
$initials .= substr($name,0,1) . ".";
}

 
Hi again

I have created a sub with the details you have given me and it works to a certain extent. The only problems is there is always two full stops at the end of the variable returned i.e. J.P.L.. OR J..

Is there anyway to sort this behaviuor out


sub shorten_initial()
{
@names = (split /\,/, $_[0]);
$init = "";
foreach $name (@names){
$init = $init . substr($name,0,1) . ".";}
return $init;
}
 
$init=~s/\.\./\./g;

Sometimes its easier to clean up afterwards ...

--Paul
 
Code:
$name = 'William,Carter,Smith';
$initials = join('.', $name =~ /(?:^|(?<=,))(\w)/g) . '.';

----------------------------------------------------------------------------------
...but I'm just a C man trying to see the light
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top