http://www.perlmonks.org?node_id=1051329


in reply to Issue with regex matching

You say you want to count how many times the variable appears in the file, but your code tries to count the number of lines that contain the variable. If you did intend the former, you can count the number of occurrences in one go:

while (<FILE>) { $count += () = /\Q$constant\E/g; } print "$constant occurs $count times\n";

In my experience, small files (anything less than several megabytes) often perform better if you slurp the whole thing in, rather than looping over each line:

use File::Slurp; my $constant = '$_'; $_ = read_file('filename.pl'); $count = () = /\Q$constant\E/g; print "$constant occurs $count times\n";