Perl script to add information to a file

Hi,
i have one hash tables that contains data stings and information. I have one c file , i need to search the file and if i found stings in the c file i need to add information at the top of the c file. I am very beginer to perl, i have written code like this
code:
#!/usr/bin/perl
use warnings;
use strict;

open (my $code , “<”, ‘c.c’);

my %strings = (‘string1’=>"information
",
‘string2’=>"information2
",
‘string3’=>"information3
",
);

my $test_string=“(” .join(“|”, keys %strings).“)” ;

while(<$code>){

if (/$test_string/){

chomp;

$.=$strings{$1};
}
print $

}

this code adding the information before the string, i need to add at the top of the c file. what should i do in this case.

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 \
",
  'string2' => "information2 \
",
  'string3' => "information3 \
",
);
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';

Hi,
thanks for your reply, i will try like this .