Perl Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 5.00

opendir.pl - Sample Program to Read Directories

This section provides a tutorial example on how to open the current directory using opendir() function and read its file names using readdir() function.

The following sample program, opendir.pl, opens the current directory twice. The first time, it reads the directory one entry at a time. The second time, it reads all entries of the directory to an array.

#- opendir.pl
#- Copyright (c) 1995 by Dr. Herong Yang, http://www.herongyang.com/
#
   print "Reading one entry at a time...\n";
   opendir(DIR,".");
   while ($f=readdir(DIR)) {
      print "$f\n";
   }
   closedir(DIR);
   print "\n";
   print "Reading all entries into an array...\n";
   opendir(DIR,".");
   @a = readdir(DIR);
   closedir(DIR);
   for (@a) {
      print "$_\n";
   }
   exit;

Now run this program by entering the program file name directly in a command window, and you will get the following output:

>opendir.pl
Reading one entry at a time...
.
..
hello.pl
hello.prg
opendir.pl

Reading all entries into an array...
.
..
hello.pl
hello.prg
opendir.pl

Note that:

  • Like Unix system, a Windows file directory has two special entries, "." and ".." representing current directory and parent directory.

Sections in This Chapter

opendir() - Open Directory to Read File Names

opendir.pl - Sample Program to Read Directories

DirTree.pl - Displaying the Directory Tree

DirGrep.pl - Searching Text in Directory Files

Dr. Herong Yang, updated in 2008
opendir.pl - Sample Program to Read Directories