Is there anyway to add the new stuff to the top of the file instead of the bottom?
Perhaps the following will be helpful:
use strict;
use warnings;
addStuffToTopOfFile( "New Stuff!\n", 'File.txt' );
sub addStuffToTopOfFile {
my ( $stuff, $file ) = @_;
local @ARGV;
local $^I = '.bak';
push @ARGV, $file;
while (<>) {
print $stuff if $. == 1;
print;
}
unlink "$file.bak";
}
File contents before running script:
Line 1
Line 2
Line 3
Line 4
File contents after running script:
New Stuff!
Line 1
Line 2
Line 3
Line 4
This solution was implicit in Anonymous Monk's reply, but you send a string and file you want prepended to the subroutine. The script makes, and then deletes, a backup file during the process. |