I have a huge file with the following lines
# run1
# word 26871
# text returns
text
text
text
# run2
# word 26872
# text returns
text
text
#run3
I would like to be able to read the file and get the following output
word 26871
number of text = 3
word 26872
number of text = 2
the program I wrote is posted below and sort of works but gives:
word 26871
number of text = 1
number of text = 2
number of text = 3
word 26872
number of text = 1
number of text = 2
I have some solutions to the above problem but they are very
inefficient some of which include - passing the counts to an array
and accessing the last element of the array that being the total
number of text counts for word. Then clearing the array and
repeating. This seems like a terribly inefficient way to solve this
problem.
I know that I should move the print "the number of text ="
outside the loop. But some of the options I have tried don't exactly
pan out.
Any advice would be much appreciated.
#!/usr/bin/perl -w
print "Type in the name of the file you want to read: ", "\n" ;
$count = 0 ;
$filename =<STDIN> ; # reads in a file that I type in.
chomp $filename ; # removes the newline after the filename
open(FILE, $filename) || die "I can't read your file, it does not exi
+st" ;
while (defined ($line = <FILE>))
{
if ($line =~ /word/) ##
{
$name = substr($word, 2, 11) ;
print "the word number is: ", $name, "\n" ;
+
$count = 0
}
elsif ($line !~ /#/)
{
$count++ ;
}
print "the number of text = ", $count, "\n" ;
}
close FILE ;
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.