0

I want to append text at beginning of "input.txt" file. Here is my code

#!/usr/bin/perl
open(FHR,">>input.txt");
seek(FHR,0,0);
print FHR "Appending at beginning of input.txt file";

But this code is appending data at end of the file. How can I modify the code!

Sanjit Prasad
  • 398
  • 2
  • 12

1 Answers1

1

You don't want to append, you want to prepend. The only possible way it to create a new file, write the new content, then copy the rest of the old file, and rename the new file to the old file's name.

my $new_filename = 'newfile.txt';
my $old_filename = 'oldfile.txt';
open my $new, '>', $new_filename or die "$new_filename: $!";
open my $old, '<', $old_filename or die "$old_filename: $!";
print {$new} "Prepending at the beginning of the file.\n";
print {$new} $_ while <$old>;
close $new;
rename $new_filename, $old_filename or die "rename: $!";
choroba
  • 231,213
  • 25
  • 204
  • 289
  • Thanks for answering. So, even if I had to add only single text then also I have to copy all content(old file) to another file and then copy the same to the new file. – Sanjit Prasad Sep 07 '18 at 17:30