
japhy
Enthusiast
Dec 15, 2000, 8:15 AM
Post #1 of 3
(38651 views)
|
Inserting Lines Into Files
|
Can't Post
|
|
This question is in the Perl FAQ, but I will include a brief summary here. If you want to append lines to a file, simply open the file for appending:
open FILE, ">> $path_to_file" or die "can't open $path_to_file: $!"; print FILE "new line\n"; close FILE; However, inserting lines into the file at other places (like the beginning, for instance) requires a bit more finessing, and so I introduce you to Perl's in-place file editing:
{ local $^I = ".bak"; # the backup extension local @ARGV = $path_to_file; # the file to edit while (<>) { next if $. == 10; # this will skip line 10 print "before line 3!\n" if $. == 3; # this appears before line 3 print; # this prints the line itself print "after line 6!\n" if $. == 6; # this appears after line 6 } } As you can see, Perl takes care of the hard part, and lets you decide how to modify the file at will. The $. variable holds the current line number, and the $_ variable holds the current line. Here is a quick way to remove all lines that start with # signs from a list of files:
{ local ($^I, @ARGV) = (".bak", @list_of_files); while (<>) { print unless /^#/; } } As you can hopefully see, I use one simple instruction to successfully weed out all lines that start with #'s. For more information, please consult the Perl FAQ, as this forum (and this list of FAQs) is not meant to be a redundant source of (possibly wrong) information. Jeff "japhy" Pinyan -- accomplished hacker, teacher, lecturer, and author
|