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

Escape characters and string length

Status
Not open for further replies.

rvBasic

Programmer
Oct 22, 2000
414
BE
Following snippet
Code:
$str="\nabc d\bef z\n";
print "\$str $str has ".length($str)." characters\n";
$cnt=0;
while ($str=~/./g){$cnt++};
print "or has it $cnt characters?\n";
displays this output:
Code:
$str 
abc def z
 has 12 characters
or has it 10 characters?

It is my understanding that the length function includes all escape characters, but that the dot drops the newline characters. Both seem to include the backspace character which apparently does not erase the preceding character in the string assigment.

Are these valid assumptions?

_________________________________
In theory, there is no difference between theory and practice. In practice, there is. [attributed to Yogi Berra]
 
There are 12 characters in the string. Your assumptions are correct.

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Also try
[tt]while($str=~/./gs){$cnt++};[/tt]
and you'll better understand why.
Note also that
[tt]$cnt=@{[$str=~/./gs]};[/tt]
should be faster, and that
[tt]$cnt=$str=~tr/\000-\377//;[/tt]
would be even faster (but not as much as [tt]length[/tt] of course).

Franco
: Online engineering calculations
: Magnetic brakes for fun rides
: Air bearing pads
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top