$`
and $'
can be used.
#!perl -nl sub maybe_print_m { $DONE_M || print "$PREFIX.M"; } $PRINTED_LINE = 1; unless (/$PREFIX/) { maybe_print_m; $DONE_M = 0; } /\./; $PREFIX = $`; if (/[M-Z]$/) { maybe_print_m unless /M$/; $DONE_M = 1; } print; END { $PRINTED_LINE&&maybe_print_m }