introduction to web programming Opening, Reading and Closing Directories Just like files, Perl gives you the ability manage directories. Specifically, Perl allows you to open a directory as a directory handle, read in the current contents of the directory and then close it again.

To open a directory, you use the following syntax:

    opendir ([FILE_HANDLE_NAME],
    "[directory_location]") || &CgiDie ("Can't
    open [directory_location]");

Thus, for example, you might open the directory "/usr/local/etc/www/" with the syntax:

    opendir (WWW, "/usr/local/etc/www/") ||
         &CgiDie ("Can't open www");

As you can see, like opening files, Perl allows the program to die elegantly in case there is a problem opening the directory. Also, as with file manipulation, you must close a directory after you are done with it using the syntax:

    closedir ([FILE_HANDLE_NAME]);

For example, to close the directory opened above, you use the command:

    closedir(WWW);

Once you have opened a directory, you can also read the contents of the directory with the readdir function. For example, the following code snippet assigns all of the filenames in the www directory to @filenames:

opendir (WWW, "/usr/local/etc/www/") ||
&CgiDie ("Can't open www");
@filenames = readdir (WWW);
closedir (WWW);

If you want to avoid including the "." (current directory) and ".." (root directory) files you can use the grep function to avoid including them in the readdir function using the syntax:

@filenames = grep (!/^\.\.?$/, readdir (FILE_HANDLE_NAME);

Previous | Next | Table of Contents