|
Write a File Perl
#!/usr/local/bin/perl
open (MYFILE, '>>data.txt');
print MYFILE "Bob\n";
close (MYFILE);
If you run this program, then run the program from the previous example
on reading a file in Perl, you'll see that it's added one more name to
the list.
Larry
Curly
Moe
In fact, every time you run the program it will add another Bob to the
end of the file. This is happening because we opened the file in append mode. To open a file in append more, just prefix the filename with the >>
symbol. This tells the open function that you want to write to the file
by tacking more onto the end of it. If instead you want to overwrite
the existing file with a new one, you can use the > single
greater than symbol to tell the open function that you want a fresh file
each time. Try replacing the >> with a > and you'll see that
your data.txt file is cut down to a single name - Bob - each time you
run the program.
open (MYFILE, '>>data.txt');
Next we use the print function to print our new name to the file. You
print to a filehandle simply by following the print statement with the
filehandle.
print MYFILE "Bob\n";
Finally we close the filehandle to finish out the program.
close (MYFILE);
|
|