Announcement:
World of Warcraft Bots, need some help in choosing the best bot?
World of Warcraft Bots, need some help in choosing the best bot?
News Archives
- We ain't dead (28-05-2008)
- The Blogkeepers (07-05-2008)
- RandomBase IRC (26-04-2008)
- Updates (17-04-2008)
- We're baaaaack (12-04-2008)
- 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.
Previous [ 1 - 2 - 3 - 4 - 5 - 6 ] Next
Statistics
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 |
#!/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);










