I don't understand exactly what you mean. I can tell you that spaces, tabs, and newline characters qualify as white spaces..... if you would like sample code, that tells you how to count the number of white spaces.... then that's a different story.

I am reading a file and trying to make a string based on the number of spaces that precedes the character that will go in the string. Does perl count each space as one character, or does it even count them at all?

Here is some code for you to count the number of "white spaces" in a file at the end of the string... the sub (function) classifies white spaces as space, tab, and newline.... you can modify the source accordingly, should it only be spaces, or only be tabs, or both... or any combo....

$file = $ARGV[0];

if ($file eq "") { 
	exit;
}


$wspace = 0;
open (FH, "$file");
	while (<FH>) {
		$nums = &count_trailing_white_spaces($_);
		$wspace += $nums;		
	}
close(FH);

print "There Are: $wspace White Spaces\n";

exit;





sub count_trailing_white_spaces
{
	$thestring = shift;
	my $wspacecnt = 0;

	while (substr($thestring, length($thestring) -1, 1) eq " " || substr($thestring, length($thestring) -1, 1) eq "\t" || substr($thestring, length($thestring) -1, 1) eq "\n") {
		$wspacecnt++;
		chop($thestring);
	}	

	return $wspacecnt;
}

Hope This Helps.

Yes, Perl Counts Spaces as 1 character...and you can modify the above sub to count from the begining of the string, and loop until it finds a normal character. The one above finds trailing white spaces.... so, it starts from the very right of the string, and loops until there are no more tabs, spaces, or newline characters trailing "normal characters". As soon as the loop reaches something that is NOT a space or a tab or a newline character, it stops the loop. To have the loop start from the begining, then you would have to modify the loop quite a bit... because I use chop to shorten the string after the white space is counted... you would have to make your own function to chop the string at the begining and work that way....

This article has been dead for over six months. Start a new discussion instead.