Opening a directory is just like opening a file. Though you will probably need to follow the full server path or symlinks to get to the directory you want. Suppose you want to open the "docs" directory, which on your server has the path "/home/username/www/docs/". You would do it like this:
-
opendir(IMD, "/home/username/www/docs/") || die("Cannot open directory");
Like a file we can make that path a variable and use it instead:
-
$getdir="/home/username/www/docs/";
-
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
-
closedir(IMD);
The whole bit from open to close looks like this:
-
$getdir="/home/username/www/docs/";
-
opendir(IMD, $dirtoget) || die("Cannot open directory");
-
@thefiles= readdir(IMD);
-
closedir(IMD);
You can use this to list the files in a directory, though not elegant as using regular expressions, it will will serve.
-
#!/usr/bin/perl
-
-
$getdir="/home/username/www/docs/";
-
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>";
This can be used as an easy way if displaying multiple items like images instead of writing a bunch of HTML code for each image, especially if their are a lot of files, handy if you are lazy or it happens to be Tuesday.