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