next up previous
Next: Reading and Writing Files Up: Some useful Perl Previous: Spilt() and join()

Reading Directories

Perl has several functions to operate on functions the opendir(), readdir() and closedir() functions are a common way to achieve this.

opendir(DIR_HANDLE,"directory") returns a Directory handle -- just an identifier (no $) -- for a given directory to be opened for reading.

Note that exact or subpath directories may be required.

BE WARNED: Macintosh directory paths are denoted by : in this instance UNIX directory paths are denoted by /.

readdir(DIR_HANDLE) returns a scalar (string) of the basename of the file (no sub directories (: or /))

closedir(DIR_HANDLE) simply closes the directory.

Therefore to list all files a given directory we can do the following:

opendir(IDIR,"Maclab:Internet") 
   || die "NO SUCH Directory: Images";

while ($file = readdir(DIR) )
  {
        print " $file\n";
    
   }
closedir(DIR);

The above reads a folder Internet on the top level of the Maclab hard disk.

On UNIX we may do:

opendir(IDIR,"./Internet") 
   || die "NO SUCH Directory: Images";

while ($file = readdir(DIR) )
  {
        print " $file\n";
    
   }
closedir(DIR);

The above reads a sub-directory Internet assumed to be located in the same directory from where the Perl script has been run.

One further example to alphabetically list files is:

opendir(IDIR,"./Internet") 
   || die "NO SUCH Directory: Images";

foreach $file ( sort readdir(DIR) )
  {
        print " $file\n";
    
   }
closedir(DIR);



Dave Marshall
9/28/2001