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

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.

Table of Contents

 About This Book

 Perl on Linux Systems

 ActivePerl on Windows Systems

 Data Types: Values and Variables

 Expressions, Operations and Simple Statements

 User Defined Subroutines

 Perl Built-in Debugger

 Name Spaces and Perl Module Files

 Symbolic (or Soft) References

 Hard References - Addresses of Memory Objects

 Objects (or References) and Classes (or Packages)

 Typeglob and Importing Identifiers from Other Packages

 String Built-in Functions and Performance

 File Handles and Data Input/Output

 Open Files in Binary Mode

Open Directories and Read File Names

 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

 File System Functions and Operations

 Converting Perl Script to Executable Binary

 Using DBM Database Files

 Using MySQL Database Server

 Socket Communication Over the Internet

 XML::Simple Module - XML Parser and Generator

 XML Communication Model

 SOAP::Lite - SOAP Server-Client Communication Module

 Perl Programs as IIS Server CGI Scripts

 CGI (Common Gateway Interface)

 XML-RPC - Remote Procedure Call with XML and HTTP

 RPC::XML - Perl Implementation of XML-RPC

 Integrating Perl with Apache Web Server

 References

 Printable Copy - PDF Version

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