[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] Counting Words



At 0.34 -0400 1999.05.21, Michael D. Kirkpatrick wrote:
>I am trying to get a word count from a string.
>
>$a="This is some sample text."
>
>I have tried this and it does not work:
>$returncount=0;
> @words=split(/\ /,$a);
> foreach $trash(sort keys(@words)){
>  $returncount++;
> }
>
>I am getting an odd number of elements in hash array error.

Ronald told you why on that ... keys() is for hashes, @keys is not a hash.
Also, you don't need to iterate over @words to get the count.  $count =
@words gives you the count (that is, putting @words in a scalar context
returns the number of elements in @words).  And if you are going to iterate
over @words just to get a count, you don't need to sort it, and you don't
need to put a dummy $trash variable there.  This is sufficient:

  for (@words) {
    $returncount++;
  }

But as I said, a simple:

  $returncount = @words;

will do what you want.  Also, you don't need to escape the space in the
regex.  / / and /\ / are the same.  But I would use a different regex.  The
one below splits on anything that is not alphanumeric (a-z, A-Z, 0-9, _) or
a dash or an apstrophe.  So "man.oh.man" would be three words, but
"man-oh-man" would be one.  If you really want to split on whitespace, a
better regex would be /\s+/, which splits on any amount of whitespace
separating non-whitespace characters.

  $text  = "This is some sample text.";
  @words = split /[^\w-']+/, $text;
  $count = @words;

--
Chris Nandor          mailto:pudge@pobox.com         http://pudge.net/
%PGPKey = ('B76E72AD', [1024, '0824090B CE73CA10  1FF77F13 8180B6B6'])

===== Want to unsubscribe from this list?
===== Send mail with body "unsubscribe" to macperl-request@macperl.org