Well for text replacement, the obvious solution is regular expressions. You should see perlrequick, perlretut, and perlre for starters. Just as an example, if your first line contains the text REPLACEME, you could do something like:
use English; # for $INPUT_LINE_NUMBER instead of $.
# open files FILE and OUT
while (<FILE>) {
s/REPLACEME/$filename/ if $INPUT_LINE_NUMBER == 1;
print OUT $_;
}
# close files
You may also want to see English and perlvar for details on $. and the $INPUT_LINE_NUMBER variables (and cousins that I haven't mentioned).