CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Frequently Asked Questions:
Inserting Lines Into Files

 



japhy
Enthusiast

Dec 15, 2000, 8:15 AM

Post #1 of 3 (25341 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:


Code
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:


Code
{ 
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:


Code
{ 
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


japhy
Enthusiast

Dec 15, 2000, 1:59 PM

Post #2 of 3 (25331 views)
Re: Inserting Lines Into Files [In reply to] Can't Post

I was asked about the $^I variable, and how to use it if you don't want to keep a backup copy. Well, if $^I is undefined, Perl will not start in-place editing mode. Therefore, set it equal to the empty string, and Perl will not keep a backup file for you.

Read more about this variable in the perlvar section of the documentation.

Jeff "japhy" Pinyan -- accomplished hacker, teacher, lecturer, and author


sleuth
Enthusiast

Feb 16, 2001, 11:58 AM

Post #3 of 3 (25260 views)
Re: Inserting Lines Into Files [In reply to] Can't Post

 
This is the best thread in the faq, bringing to front. :)

Tony


 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives