viswa
viswa

Reputation: 61

how to add information at the start of the file using perl

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" question. 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.

Upvotes: 0

Views: 204

Answers (2)

Dave Sherohman
Dave Sherohman

Reputation: 46187

(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';

Upvotes: 0

Related Questions