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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help with split

Status
Not open for further replies.

juletools

IS-IT--Management
May 2, 2002
12
GB
Hi All

Apologies in advance if this is a dumb question.

I'm trying to separate out digits from an alphanumeric string and then load these into an array using the following.

E.g $string = 1test123

@stringdigits = split(/\D/, $string);

What I wanted to happen was that only the 1,2,3,4 were read and they were separately loaded into the array as:

$stringdigits[0], $stringdigits[1], $stringdigits[2], $stringdigits[3]

What seems to be happening is that the letters are being loaded into the array as empty elements and the numbers are not being separated as I expected. I know strings can be separated into individual characters using:

@indivchars = split(//, $string);

Do I need to somehow combine the two? What am I doing wrong?

Any help would be much appreciated.
Thanks
J
 
Using a delimiter of [tt]\D[/tt] would, I would think, get you:
[tt]@stringdigits = ("1", "", "", "", "123")[/tt]

That's because the delimiter is any (single) non-digit character. Closer to what you want would be:
[tt]@stringdigits = split(/\D+/, $string)[/tt]

which would get you:
[tt]@stringdigits = ("1", "123")[/tt]

To get exactly what you want:
[tt]@stringdigits = map { split(//, $_); } split(/\D+/, $string);[/tt]

This takes each of the elements created by the split and splits them into single characters.
 
And if you are not wedded to using split:
Code:
my @stringdigits = $string =~ /\d/g;
jaa
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top