in reply to Perlish while loop

You could consider using File::Basename to extract the filename.
use File::Basename; # ... while (<$fh>) { chomp; if (/^M/) { my $filename = fileparse($_); # ... } }
It has as an additional benefit that it takes care of the different file-path separators on Unix, Windows, Mac, VMS, ..., making your script more compatible with different OSs.

CountZero

A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James