Some standard functions for operating directories are listed below:
Opendir DIRHANDLE, EXPR # Open directory
Readdir DIRHANDLE # Read Directory
Rewindir DIRHANDLE # Positioning pointer to beginning
Telldir DIRHANDLE # Returns the current location of the directory
Seekdir DIRHANDLE, POS # Locate the POS location specified in the directory
Closedir DIRHANDLE # Close directory
5.36.1. Show all files #
Displays all files in the directory, and the following example uses the The following example lists all files in the current directory: If you want to show
glob
operator, demonstrated as follows:Example #
#!/usr/bin/perl# display /tmp
All files in the directory$dir="/tmp/*";my@files=glob($dir);foreach(@files){print$\_."\\n";}#
display /tmp All files in the directory.c
Ending file$dir="/tmp/*.c";@files=glob($dir);foreach(@files){print$\_."\\n";}#
Show all hidden files$dir="/tmp/.*";@files=glob($dir);foreach(@files){print$\_."\\n";}#
display /tmp and /home All files in the directory $dir="/tmp/*
/home/*";@files=glob($dir);foreach(@files){print$\_."\\n";}
Example #
#!/usr/bin/perlopendir(DIR,'.')ordie"Unable to open directory,$!";
while($file=readdirDIR){print"$file\\n";}closedirDIR;
/tmp
all the contents of the directory with `` .c``at the end of the file, you can use the following codeExample #
#!/usr/bin/perlopendir(DIR,'.')ordie"Unable to open directory,$!";
foreach(sortgrep(/^.*\.c$/,readdir(DIR))){print"$\_\\n";}closedirDIR;
5.36.2. Create a new directory #
We can use it.
mkdir
function to create a new directory, you need to have sufficient permissions to create a directory before execution:
5.36.3. Example #
#!/usr/bin/perl$dir="/tmp/perl";# Create perl in the/tmp directory
directory mkdir($dir)ordie"could not be built $dir directory,$!";
print"Directory created successfully\\n";
5.36.4. Delete directory #
We can use it.
rmdir
function to delete the directory, which requires sufficient permissions. In addition, the empty directory required for the directory to be deleted:Example #
#!/usr/bin/perl$dir="/tmp/perl";# delete /Perl under tmp directory
directory rmdir($dir)ordie"Unable to delete $dir directory,$!";
print"Directory deleted successfully\\n";
5.36.5. Switch directories #
We can use it. Execute the above program, and the output is as follows:
chdir
function to switch current directories, and sufficient permissions are required to perform this operation. Examples are as follows:Example #
#!/usr/bin/perl$dir="/home";# Move current directory to /home
Under the directory chdir($dir)ordie" Unable to switch directory to $dir,
$!";print" The directory you are currently in is $dir\\n";
The directory you are currently in is /home