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.
There's also another method of reading data from a file - a loop that will run through the file, printing one line after another:
#!/usr/bin/perl
# open file and define a handle for it
open(MIND,"thoughts.txt");
# assign the first line to a variable
$line = <MIND>;
# use a loop to keep reading the file
# until it reaches the end
while ($line ne "")
{
print $line;
$line = <MIND>;
}
# close file when done
close(MIND);
# display message when done
print "Done!\n";
Well, it works - but how about making it a little more
efficient? Instead of reading a file line by line, Perl also allows you to suck the entire thing straight into your program via an array variable - much faster, and definitely more likely to impress the girls!
Here's how:
#!/usr/bin/perl
#pen file and define a handle for it
open(MIND,"thoughts.txt");
# suck the file into an array
@file = <MIND>;
# close file when done
close(MIND);
# use a loop to keep reading the file
# until it reaches the end
foreach $line (@file)
{
print $line;
}
# display message when done
print "Done!\n";
As you can see, we've assigned the contents of the file
"thoughts.txt" to the array variable @file via the file handle. Each element of the array variable now corresponds to a single line from the file. Once this has been done, it's a simple matter to run through the array and display its contents with the "foreach" loop.
This article copyright Melonfire 2000. All rights reserved.