in reply to How NOT to do it

if from your snippet shows that that there's a space in the split @temp=split / /, $string; instead of @temp=split //, $string; maybe what he wanted to do is to count number of words in the string.. which can also be done like this
$ths = "this is a string"; $i=split(/\s/,$ths); print $i;

Replies are listed 'Best First'.
Re: Re: How NOT to do it
by danger (Priest) on Mar 19, 2001 at 14:00 UTC

    That is not what the original code snippet does (it does in fact count the string length .. hence the variable named $string_length). If you pasted the code into your editor you could see if there was a space in the regex or not (not). Your code to count words, however, not only isn't -w compliant (implicit split to @_), it can very easily give wrong results:

    $ths = ' this is a string'; $i = split(/\s/,$ths); print "$i\n";

    If you want to split a string on whitespace, use the special case of split(" ", $ths) which splits on multiple whitespace and ignores any leading null field (see: perlfunc:split for details).

    $_ = ' this is a string'; my @words = split " "; print scalar @words, "\n"; # or you could go for this version :-) $_ = ' this is a string'; my $words =()= /(\S+)/g; print $words, "\n";