How big is this file and how many keywords will you look for? This seems like you are going to take up a lot of time. Not only that, but simply finding a substring in the line doesn't mean that it was used as a java keyword (although you may have some other definition). For instance, you might not want to count strings that appear as comments.

Why not use a Java source code parser, then walk the tree pulling out the keywords and their line numbers? It might not be in Perl (there seem to be many Java implementations), but at least it has a chance of being right. :)

For the general situation that you're using so far, you just need to add a counter hash. You could simply count:

if( $line =~ /$keyword/ ) { $Counter{ $keyword } ++; ...

Or you could do something more fancy, such as remembering the line numbers.

# Initialize the counter my %Counter = map { $_, [] } @keywords; while( my $line = <INPUT> ) # one line at a time { ... if( $line =~ /$keyword/ ) { # $. is the current input line number push @{ $Counter{ $keyword } }, $.; ... }

Good luck :)

--
brian d foy <brian@stonehenge.com>
Subscribe to The Perl Review

In reply to Re: Improving a script to search for keywords in a file by brian_d_foy
in thread Improving a script to search for keywords in a file by stort83

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.