First attempt (589 strokes)

#!perl -w
use strict;
use IO::Handle;
my ($DONE_M, $PREFIX, $PRINTED_LINE);
$PREFIX = "";
sub maybe_print_m {
    unless ($DONE_M) {
	print "$PREFIX.M"
    }
}
if (@ARGV) {
    open STDIN,  "<", shift @ARGV;
}
if (@ARGV) {
    open STDOUT, ">", shift @ARGV;
}
IO::Handle->output_record_separator("\n");
while (<>) {
    $PRINTED_LINE = 1;
    chomp;
    unless (/$PREFIX/) {
	maybe_print_m;
	$DONE_M = 0;
    }
    my $s;
    ($PREFIX, $s) = split /\./, $_, 2;
    if (/[M-Z]$/) { 
	unless (/M$/) {
	    maybe_print_m;
	}
	$DONE_M = 1;
    }
    print;
}
if ($PRINTED_LINE) {
    maybe_print_m;
}