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.
Like all widely-used programming languages, Perl has the very useful ability to read data from, and write data to, files on your system. It accomplishes this via "file handles" - a programming construct that allows Perl scripts to communicate with data structures like files, directories and other Perl scripts.
Although you might not have known it, you've actually already encountered file handles before. Does this look familiar?
#!/usr/bin/perl
# ask a question...
print "Gimme a number! ";
# get an answer...
$number = <STDIN>;
# process the answer...
chomp($number);
$square = $number * $number;
# display the result
print "The square of $number is $square\n";
If you remember, we told you that the <STDIN> above
refers to STanDard INput, a pre-defined file handler that allows you access information entered by the user. And just as <STDIN> is a file handler for user input, Perl allows you to create file handles for other files on your system, and read data from those files in a manner very similar to that used above.
For our first example, let's assume that we have a text file called "thoughts.txt", containing the following random thoughts:
We're running out of space on planet Earth.
Scientists are attempting to colonize Mars.
I have a huge amount of empty real estate in my mind.
Imagine if I could rent it to the citizens of Earth for a nominal monthly
fee.
Would I be rich? Or just crazy?
Now, in order to read this data into a Perl program, we need
to open the file and assign it a file handle - we can then interact with the data via the file handle.
#!/usr/bin/perl
# open file and define a handle for it
open(MIND,"thoughts.txt");
# print data from handle
print <MIND>;
# close file when done
close(MIND);
# display message when done
print "Done!\n";
And when you run this script, Perl should return the contents
of the file "thoughts.txt", with a message at the end.
A quick explanation: in order to read data from an external file, Perl requires you to define a file handle for it with the open() function. We've done this in the very first line of our script.
open(MIND,"thoughts.txt");
You can specify a full path to the file as well:
open(MIND,"/home/user1/thoughts.txt");
In this case, MIND is the name of the file handle, and
"thoughts.txt" is the text file being referenced. The file will then be read into the file handle <MIND>, which we can use in much the same manner as we would a variable. In the example above, we've simply printed the contents of the handle back out with the print() function.
Once you're done with the file, it's always a good idea to close() it - although this is not always necessary, it's a good habit!
This article copyright Melonfire 2000. All rights reserved.