This week's article teaches you how to use Perl to interact withfiles on your system, and also provides you with a quick crash course invarious array functions.
Obviously, reading a file is no great shakes - but how about writing to a file? Well, our next program does just that:
#!/usr/bin/perl
# open file for writing
open(BRAINWASH,">wash.txt");
# print some data to it
print BRAINWASH "You will leave your home and family, sign over all your
money to me, and come to live with forty-six other slaves in a tent until I
decide otherwise. You will obey my every whim. You will address me as The
Great One, or informally as Your Greatness.\n";
# close file when done
close (BRAINWASH);
Now, once you run this script, it should create a file named
"wash.txt", which contains the text above.
$ cat wash.txt
You will leave your home and family, sign over all your money
to me, and come to live with forty-six other slaves in a tent until I
decide otherwise. You will obey my every whim. You will address me as The
Great One, or informally as Your Greatness.
$
As you can see, in order to open a file for writing, you
simply need to precede the filename in the open() function call with a greater-than sign. Once the file has been opened, it's a simple matter to print text to it by specifying the name of the appropriate file handle in the print() function call. Close the file, and you're done!
The single greater-than sign indicates that the file is to be opened for writing, and will destroy the existing contents of the file, should it already exist. If, instead, you'd like to append data to an existing file, you would need to use two such greater-than signs before the filename, like this:
# open file for appending
open(BRAINWASH,">>wash.txt");
This article copyright Melonfire 2000. All rights reserved.