Perl directory operation


Release date:2023-10-19 Update date:2023-10-21 Editor:admin View counts:242

Label:

Perl directory operation

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

Show all files

Displays all files in the directory, and the following example uses the 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";}

The following example lists all files in the current directory:

Example

#!/usr/bin/perlopendir(DIR,'.')ordie"Unable to open directory,$!";
while($file=readdirDIR){print"$file\\n";}closedirDIR;

If you want to show /tmp all the contents of the directory with ``.c``at the end of the file, you can use the following code

Example

#!/usr/bin/perlopendir(DIR,'.')ordie"Unable to open directory,$!";
foreach(sortgrep(/^.*\.c$/,readdir(DIR))){print"$\_\\n";}closedirDIR;

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:

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";

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";

Switch directories

We can use it. 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";

Execute the above program, and the output is as follows:

The directory you are currently in is /home

Powered by TorCMS (https://github.com/bukun/TorCMS).