Reading Directories
Open a Directory
Opening a directory is very much like opening a file. Suppose you want to open the "images" directory, which on your server has the path "/home/yourname/www/images/". You would do it like this:opendir(IMD, "/home/yourname/www/images/") || die("Cannot open directory");
Like a file, we use a handle for the directory for later use. Then we call the path to the directory. As in other sections, we can make that path a variable and use it instead:
$dirtoget="/home/yourname/www/images/";
opendir(IMD, $dirtoget) || die("Cannot open directory");
Now that it is open, we will want to read in the contents.
Read the Contents
The contents of the directory will be the file name of each file in the directory, including "." and ".." in the list. You'll want to toss those two out if you want just the files themselves. To read the directory, we can read the contents into an array and use the array:@thefiles= readdir(IMD);
Use the handle you assigned to your directory in the readdir command. In our case, it is IMD. Now the contents of the images directory are in the @thefiles array.
Close the Directory
Again, pretty much the same, just use closedir with the directory handle:closedir(IMD);
The whole bit from open to close looks like this:
$dirtoget="/home/yourname/www/images/";
opendir(IMD, $dirtoget) || die("Cannot open directory");
@thefiles= readdir(IMD);
closedir(IMD);
You can use this to list the files in a directory, for example. So, suppose we want to list all the image files in the images directory. We could write something like this:
#!/usr/bin/perl
$dirtoget="/home/yourname/www/images/";
opendir(IMD, $dirtoget) || die("Cannot open directory");
@thefiles= readdir(IMD);
closedir(IMD);
print "Content-type: text/html\n\n";
print "<html><body>";
foreach $f (@thefiles)
{
unless ( ($f eq ".") || ($f eq "..") )
{
print "$f<br />";
}
}
print "</body></html>";
Of course, the unless statement isn't the most elegant way to pull out the "." and ".." values, but we'll save that for some sections on regular expressions. The rest is just printing each file name on a line. The output would be something like this, though the number of file names could be more or less:
logo.gif
button.gif
banner.gif
mypic.jpg
background.jpg
Of course, you can do more useful things with it, this can be a great way to grab the file names and make use of them for dispaly, if you wanted to display everything in your images directory without writing a bunch of HTML code (handy if the list is long).
Well, that's all for now, let's go on to: Using Environment Variables.
