DIRECTORY
Main Menu
Affiliate Programs
Hosting
Traffic
Content
BillinG
Design
show pic archive
Articles
Tutorials
interviews
jbm newsletteRS
jbm JOBS BOARD
Contact Us
Message Board

Advertising inquiries


 
Tutorials - How To Read And Write Perl Data Files

How to use Perl data files

In Perl, reading and writing to files is pretty straightforward. First you have to open a file. Depending on your task, you read data from or write data to the file, then you close it.
How to open files in Perl

To open a file in Perl, use the open function.

=======
open( FILE_HANDLE, filename) or die "Your message goes here\n" ;
=======

Although die is not required, things can and do go wrong and in most cases it's unwise or unproductive to continue the script. Including die will help you verify that your files are being opened properly, and it'll help you debug the script if they aren't.

The first variable passed to open is the name of your file handle. By convention, they are in all capital letters. Typical examples are FD (for File Descriptor), INPUT, OUTPUT, INFILE, OUTFILE, DATAFILE, etc. You can choose any name you want, but if you use capitals you'll easily separate variables from file handles. Perl doesn't care, but it'll make your code easier to read.

The second variable is the name of the actual file. Included in the filename variable is an indication of how you want the file opened: for reading, writing, or appending. The technical name for this indication is mode, and each mode is represented with the symbols < and >, as discussed below.
How to read from a Perl file

Use read mode, or '<' to read data from a Perl file.

=======
open(FD, "< test.dat") or die("Couldn't open test.dat\n") ;
=======
How to write to a Perl file

Use write mode when you want to save data to a file in Perl. Be careful since write mode will overwrite any data currently in the file. You would use this mode for things like counters, since you'd want to increment the number in the file every time someone views your page. You don't need to record every single time the value was updated, you just need the latest number. In this case, overwriting the data in your file makes the most sense.

=======
open(FD, "> test.dat") or die("Couldn't open test.dat\n") ;
=======
How to add data to an existing Perl file

Use append mode when you want to open a file for writing without destroying the current contents. Instead, any new information is added to the end of the file, and anything that already existed is kept intact.

A guestbook is a good example of when to use append mode. In this case, write mode would be a disaster, since the only thing saved in your file would be the information from your latest guest. Obviously, you don't want to overwrite data from people who are signing up!

=======
open(FD, ">> test.dat") or die("Couldn't open test.dat\n") ;
=======

 

more to come!

 

 

Work up through information obyained at About.com

Please pass on any suggestions or comments to Shok.