I need to write a Perl script that counts all occurrences of the word and in the standard input file. If the word is an “and”, print out the number of word in the line of text and the line number of the line.
I have tried to write this, however I am stuck and was I have written is not working. This is what I have so far.
#!/usr/bin/perl
$wordcount=0;
$line = <STDIN>;
chomp($line);
WHILE ($line ne "")
{
@array=split(/ /, $line);
for ($i=1; $i<@array; i++)
{
print $i;
}
if ( @array =~ /^and/gi)
{
$wordcount += @array;
}
$line= <STDIN>;
}
print("Total number of works is $wordcount \n");
Trying to generate an output that says something like this for each word occurence:
The word
and
occurred in Line 1 as the 7th word
The word
and
occurred in Line 1 as the 11th word
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.