Perlaccess : Tutorials : File and Directory
Removing Lines from a File (4.3)
by Jacob A. Wheeler
http://www.bigresources.com

Now i'm going to show you a little more advanced saving/modifying code. To make it a little easier I am going to create a scenario with a problem.

Problem: The week before your big birthday party you get into a fight with your good friend Bob. And in anger you dis-invite Bob to your party. To make sure you remembered everyone you invited to your party you stored all there names in a text file, located here. Now using perl, you would like to remove Bob's name from the file. And the below code will do just that:

  1. open(FILE,"<file.txt");
  2. @LINES = <FILE>;
  3. close(FILE);
  4. open(FILE,">file.txt");
  5. foreach $LINE (@LINES) {
  6. @array = split(/\:/,$LINE);
  7. print NEWLIST $LINE unless ($array[0] eq "Bob");
  8. }
  9. close(FILE);

Ok, don't get frustrated if you don't understand somthing! Below I have listed the same code, with comments of whats happening.

  1. open(FILE,"<file.txt"); # See Line 1
  2. @LINES = <FILE>;
  3. close(FILE); #Close the file
  4. open(FILE,">file.txt"); #Re-Open the file for modification
  5. foreach $LINE (@LINES) { # See Line 5
  6. @array = split(/\:/,$LINE); # See Line 6
  7. print NEWLIST $LINE unless ($array[0] eq "Bob"); # See Line 7
  8. } #Close off the bracket, VERY IMPORTANT.
  9. close(FILE); #Close the file

Line: 1
Opening the file 'file.txt' for input, and assigning file handle 'FILE'.

Line: 2
Load the contents of 'file.txt' into an array (@LINES) via the file handle FILE.

Line: 5
Loop through each line of the file, assigning the current line to: $LINE.

Line: 6
This code will split the current line ($LINE) into an array, using ':' as a delimeter.

Line: 7
This is the most important piece of code for what were doing. This re-writes each line of 'file.txt' back as long as the first variable in the array ($array[0]) DOES NOT equal bob. See arrays for more information, or if your confused about there setup.