(Перекрестное сообщение с ответом, который я только что дал на форумах SitePoint на тот же вопрос.)
К сожалению, нет способа вставить информацию в начало файла без необходимости перезаписывать его целиком, поэтому вам нужно будет прочитать весь файл (а не только одну строку за раз), определить, какая строка появляются в содержимом, записывают соответствующий информационный элемент (ы) в новый файл и (наконец!) записывают исходное содержимое в новый файл:
#!/usr/bin/env perl
use strict;
use warnings;
use File::Slurp;
my %strings = (
'string1' => "information \n",
'string2' => "information2 \n",
'string3' => "information3 \n",
);
my $test_string = "(" . join("|", keys %strings) . ")";
# First make a list of all matched strings (including the number of times
# each was found, although I assume that's not actually relevant)
my $code = read_file('c.c');
my %found;
while ($code =~ /$test_string/g) {
$found{$1}++;
}
# If %found is empty, we didn't find anything to insert, so no need to rewrite
# the file
exit unless %found;
# Write the prefix data to the new file followed by the original contents
open my $out, '>', 'c.c.new';
for my $string (sort keys %found) {
print $out $strings{$string};
}
print $out $code;
# Replace the old file with the new one
rename 'c.c.new', 'c.c';