RandomBase.com logo
Announcement:
World of Warcraft Bots, need some help in choosing the best bot?

News Archives

Statistics

  • There are 13 users online.
  • Most users ever online was 424 on 03/16/08.
  • Our poor server had to serve 32 pages in the last 15 minutes.
  • And yet he managed to generate this page in 0.007 seconds.

Affiliates & friends

RandomBase.com isn't just one website - it is more.

File handling in Perl

Perl is known for its quick way of reading and writing files. It's perfect to use plain text files as a database to store its data.



Naming your file handle

Perl doesn't use a standard variable when it refers to a file. You can choose about any alphanumeric name as an alias in your script for writing the file. In this tutorial, I'll name the filehandle RANDOMFILE.



Opening the file

Before opening a file you should ask yourself the question: "What am I going to use this file for?". Reading or writing? Perl gives you a variety of choices to choose from. This table shows the symbol + the appropriate action:
 > Writes only, clears/creates file first.
 >> Add data to the end of the file. Creates file if it didn't exist
 < Read-only
 +< Reading + writing
 +> Reading, writing, clears & creates file first
 +> Reading, writing, appends & creates file first
So after deciding what you want to do, let's open the file with the correct parameter! In this example, I want to write to a file but clear it first, so I'll use this code:


#!/usr/bin/perl

open(RANDOMFILE,">file.txt");




Writing to the file

Not much to say, just 'print' your data to the filehandle!

#!/usr/bin/perl

open(RANDOMFILE,">file.txt");
print RANDOMFILE "Some fun data.";




...and closing it again

Yet another easy part, close() it!

#!/usr/bin/perl

open(RANDOMFILE,">file.txt");
print RANDOMFILE "Some fun data.";
close(RANDOMFILE);




Reading the file

If you want to read a file, you have two options to consider first:
1. Do I read the whole file at once?
2. Do I read it line by line to save memory?
The second option is best for large files.


Reading the whole file at once into the memory.



#!/usr/bin/perl

open(RANDOMFILE,"<file.txt"); #Notice the read-only switch
@lines = <RANDOMFILE>;
foreach $line(@lines)
{
	print "$line\n";
}
close(RANDOMFILE);

Reading the file line by line.



#!/usr/bin/perl

open(RANDOMFILE,"<file.txt"); #Notice the read-only switch
while($line = <RANDOMFILE>)
{
	print $line;
}
close(RANDOMFILE);