i have c file and i need to add some information at the begging of the c file. I have one hash table with keys as the numbers and values as the strings. by using that table i am searching if the string found i am adding information to c file. i did this by using script i posted in " add information to a file using perl" 开发者_如何学JAVAquestion. now i need to add information at the beginging of the c file if i found string.In my script i am adding before the string. what should i do now. thanks in advance.
This is a FAQ.
How do I change, delete, or insert a line in a file, or append to the beginning of a file?
(Cross-posted from the answer I just gave on the SitePoint forums to what appears to be the same question.)
Sadly, there's no way to insert information at the beginning of a file without having to rewrite the whole thing, so you'll need to read in the entire file (rather than just one line at a time), determine which string(s) appear in the contents, write the corresponding information item(s) to a new file, and (finally!) write the original contents to the new file:
#!/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';
精彩评论