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:

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.