Listed below are some of the standard functions for manipulating directories:
opendir DIRHANDLE, EXPR # Open the directory readdir DIRHANDLE # Read the directory rewinddir DIRHANDLE # Position the pointer to the beginning telldir DIRHANDLE # Return the current position of the directory seekdir DIRHANDLE, POS # Locate the POS position specified to the directory closedir DIRHANDLE # Close the directory
Show all files
Display all files in the directory. The following example uses the glob operator, as demonstrated below:
Example
#!/usr/bin/perl # Display all files in the /tmp directory $dir = " /tmp/* " ; my @files = glob ( $dir ) ; foreach ( @files ) { print $_ . " n " ; } # Display all files ending with .c in the /tmp directory $dir = " /tmp/*.c " ; @files = glob ( $dir ) ; foreach ( @files ) { print $_ . " n " ; } # Show all hidden files $dir = " /tmp/.* " ; @files = glob ( $dir ) ; foreach ( @files ) { print $_ . " n " ; } # Display all files in /tmp and /home directories $dir = " /tmp/* /home/* " ; @files = glob ( $dir ) ; foreach ( @files ) { print $_ . " n " ; } The following example can list all files in the current directory:
Example
#!/usr/bin/perl opendir ( DIR , ' . ' ) or die " Cannot open directory, $! " ; while ( $file = readdir DIR ) { print " $file n " ; } closedir DIR ; If you want to display all files ending with .c in the /tmp directory, you can use the following code:
Example
#!/usr/bin/perl opendir ( DIR , ' . ' ) or die " Cannot open directory, $! " ; foreach ( sort grep ( /^.*. c $/, readdir ( DIR ) ) ) { print " $_ n " ; } closedir DIR ; Create a new directory
We can use the mkdir function to create a new directory. You need to have sufficient permissions to create the directory before executing:
Example
#!/usr/bin/perl $dir = " /tmp/perl " ; # Create a perl directory under the /tmp directory mkdir ( $dir ) or die " Cannot create $dir directory, $! " ; print " Directory created successfully n " ; delete directory
We can use the rmdir function to delete a directory. Sufficient permissions are required to perform this operation. In addition, the directory to be deleted must be an empty directory:
Example
#!/usr/bin/perl $dir = " /tmp/perl " ; # Delete the perl directory under the /tmp directory rmdir ( $dir ) or die " Cannot delete $dir directory, $! " ; print " Directory deleted successfully n " ; Switch directory
We can use the chdir function to switch the current directory. Sufficient permissions are required to perform this operation. Examples are as follows:
Example
#!/usr/bin/perl $dir = " /home " ; # Move the current directory to the /home directory chdir ( $dir ) or die " Cannot switch directory to $dir , $! " ; print " The directory you are currently in is $dir n " ; Executing the above program, the output result is:
The directory you are currently in is /home