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

Counting Blank Spaces in string (Stupid question) 3

Status
Not open for further replies.

Edge118

Programmer
Joined
Jun 15, 2004
Messages
104
Location
US
$data = "Hello There";

How do I count the number of spaces in the string $data?

I know this is an easy question and I was reading through the posts that had questions similar to this, but I couldn't comprehend. Thanks.

"Pin me. Perl me."

Regards,

Chris
 
Hi Edge,

you should be able to count the number of spaces in $data by applying the following:

Code:
++$count while $data =~ /\s/g;

hope this helps..
 
I think this will work:
Code:
$count = ($data =~ tr/\s/\s/);

 
Should this be:
Code:
$count = ($data =~ tr/ / /);

From [tt]man perlop[/tt]:
Note that "tr" does not do regular expression character classes
such as "\d" or "[:lower:]".


From what I deduce that [tt]\s[/tt] is not recognized in [tt]tr[/tt].

If you really need [tt]\s[/tt] (i.e any spacing character) use parkers' solution.

--------------------

Denis
 
I actually did see that line in perlop but still tested with the \s and it worked fine. BUT, it looks like I didn't test very well and it was random chance I got the right count. Good catch Denis!

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top