Saturday, May 31, 2014

Count the number of words in a statement

Script

#!/usr/bin/perl

print ("Enter a statement about something of interest to you:\n");
print ("Press Enter key and Ctrl D when done:\n\n");
$wordcount = 0;
$line = <STDIN>;

while ($line ne "")
        {
        chop ($line);
        @array = split(/ /, $line);
        $wordcount += @array;
        $line = <STDIN>;
        }
print ("The total number of words in the input is: $wordcount \n");


Execution

Enter a statement about something of interest to you:
Press Enter key and Ctrl D when done:

Rahul Dravid has won more Test matches than any other batsman in the history of Indian cricket
The total number of words in the input is: 17




Enter a statement about something of interest to you:
Press Enter key and Ctrl D when done:

Sachin Tendulkar has scored more runs and more centuries in Test cricket and One Day Internationals than anybody else in the history of the game.
The total number of words in the input is: 25


No comments:

Post a Comment