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

split still giving whitespace

Status
Not open for further replies.

jerehart

Programmer
Joined
Jun 10, 1999
Messages
61
Location
US
I am trying to remove all white space doing the following:

@DATA = split (/[\ \t\n]+/,$string);

but the first value sometimes give me a space, b/c sometimes the first part of the string is a space how do I get rid of that?
 
$string=~s/^\s+//;
@DATA = split (/[\ \t\n]+/,$string);
 
From the perlfunc manpage:

"If PATTERN is also omitted, splits on whitespace (after skipping any leading whitespace)."

That means you should just be able to say:
Code:
@DATA = split(//,$string);
Tracy Dryden
tracy@bydisn.com

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
 
I did try that at first and for the data set I am using it just wiped everything out. But thanks for both the answers.

 
What do you mean by "just wiped everything out"? One or the other of the example should have worked, unless there is something else wrong.
Tracy Dryden
tracy@bydisn.com

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
 
Oops sorry, it made sense to me they way I answered since I tried both.

When I tried:
@DATA = split(//,$string);

it cleared out all of my data. I think this is because some characters were repeated several times in the string. When I tried:

$string =~ s/^\s+//;
@data = split (/[\ \t\n]+/$string);

I got back the data the way I wanted.

 
Actually, what happened when you used split(//,$string) is that it split the string apart at EACH CHARACTER, which is obviously not what you wanted. When the perlfunc manpage said "If PATTERN is also omitted..." it didn't say HOW to omit the pattern, and I guessed that just using // was the way. I WAS WRONG! :~/ Actually, you apparently can't omit the pattern unless you omit everything! Since the default variable to split is $_, you can assign your string to that before splitting. I tried the following and it worked like a charm:
Code:
$_ = $string;
@DATA = split;
It strips off leading and trailing spaces, then splits on whitespace. It's probably more efficient than the other way.
Tracy Dryden
tracy@bydisn.com

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top