Had you turned on strict, Perl would have told you that where
you match $string that variable is out of scope.
What you do is, in a loop, read in each file, store the
context in a lexical variable (which is gone at the next
iteration of the loop). Then, outside the loop, after discarding the content of all the files, you do the matching.