in reply to Improving a script to search for keywords in a file

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