1. Perl
  2. builtin functions
  3. here

opendir function - opens a directory

You can use the opdndir function to open a directory and get a directory handle.

opendir directory handle directory name

Specify an undefined variable for the directory handle. Use the opendir function as follows:

# Directory name
my $dir = 'study';

# Open directory
opendir my $dh, $dir
  or die "Can't open directory $dir:$!"

An undefined variable is specified in the first argument, but variable declaration by my is performed at the same time. The second argument specifies the directory name.

If the directory opening fails, a false message will be returned, so you need to handle the error. Use or operator to describe the processing when a failure occurs.

die function raises an exception and terminates the program.

predefined variable "$!" is assigned the reason why the directory open failed, so be sure to include it in the error message.

How to read the contents of a directory?

Use the readdir function to actually read the contents of the directory. The readdir function is explained below.

  • ->

How to close the directory handle?

The directory handle is automatically released when scope is finished, so there is no need to explicitly close it. This is because the destructor runs when there are no more reference to the directory handle.

{
  # Directory name
  my $dir = 'study';

  # Open directory
  opendir my $dh, $dir
    or die "Can't open directory $dir:$!"
}

# The directory handle is automatically closed when the scope ends

If you want to explicitly close the directory handle, use closedir function.

closedir $dh;

Related Informatrion