I'd prefer using a hash, but since you didn't say how big your input files could be and apparently don't need to store the data for any further use, your approach of processing it line by line is just fine. What you have is close - just move a few of the variables around and that should about do it. Here is one way (it's not as elegant as a hash, but it is more like your original code)(tested):

# use the actual error for open open(FILE, $filename) || die "Error opening $filename: $!"; my ( $word, $count ); # move these out of the loop while (defined ($line = <FILE>)) { if ($line =~ /^# word (\d+)/) # tighten up regex a bit { if( defined $word ) { # print the results for the previous block print "the word number is: $word\n"; print "number of text = $count\n"; } $word = $1; $count = 0; } elsif ($line !~ /#/) { $count++; } } # print the results for the last block of data before eof print "the word number is: $word\n"; print "number of text = $count\n"; ** output from your example data ** the word number is: 26871 number of text = 3 the word number is: 26872 number of text = 2

Good job using warnings, but you should also use strict.

Update: I see gaal beat me to the punch. I guess that's what I get for testing... ;)


In reply to Re: Counting between the lines by bobf
in thread Counting between the lines by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.