counting words in a sentance

  • Hiei
  • Beginner
  • Beginner
  • Hiei
  • Posts: 51

Post 3+ Months Ago

i want to make a program that counts the total words in a sentance and compares that to a benchmark set by the user. but i don't know how you c ount the words in a sentance? my code in perl is this


Code: [ Select ]

print "type in your sentance here: ";

$words = <stdin>;
chomp ($words);

print "now type a benchmark to compare with: ";
$bench = <stdin>;
chomp ($bench);
if ($words lt $bench) { $words is less than $bench };
if ($words gt $bench) { $words is more than $bench };
  1. print "type in your sentance here: ";
  2. $words = <stdin>;
  3. chomp ($words);
  4. print "now type a benchmark to compare with: ";
  5. $bench = <stdin>;
  6. chomp ($bench);
  7. if ($words lt $bench) { $words is less than $bench };
  8. if ($words gt $bench) { $words is more than $bench };
it comes up with errors when i run it and i can't fix them, but i don't think this is the right way.
  • Anonymous
  • Bot
  • No Avatar
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post 3+ Months Ago

  • rtm223
  • Mastermind
  • Mastermind
  • User avatar
  • Posts: 1855
  • Loc: Uk

Post 3+ Months Ago

http://www.comp.leeds.ac.uk/Perl/split.html

Thats how I'd do it, I know no perl at all but I would split the string at each space and then count the number of elements in the resultant array. Then unset the array (so you are not wasting memory)
  • Hiei
  • Beginner
  • Beginner
  • Hiei
  • Posts: 51

Post 3+ Months Ago

so i just make a new variable and store the split version of $words in it? i read it and i've used the split function like this
Code: [ Select ]
$words = split(words);
print "$words";
  1. $words = split(words);
  2. print "$words";
is that how i would do it? i didn't really understand that explanation that well..
  • rtm223
  • Mastermind
  • Mastermind
  • User avatar
  • Posts: 1855
  • Loc: Uk

Post 3+ Months Ago

Well, as I said Idon't know perl, but as far as I can guess:

Code: [ Select ]
@wordCount = split(/ /, $words);


Then, according to this page:
http://www.developingwebs.net/perl/arrays.php

you can use $#wordCount to find the number of elements in the @wordcount array. As the @wordcount array consists of the sentece, with each word=separate element, number of elements=number of words.

Post Information

  • Total Posts in this topic: 4 posts
  • Users browsing this forum: No registered users and 77 guests
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
 

© 1998-2014. Ozzu® is a registered trademark of Unmelted, LLC.