Perl directory operation

Here are some of the standard functions for the operation directory:

opendir DIRHANDLE, EXPR  # 打开目录
readdir DIRHANDLE        # 读取目录
rewinddir DIRHANDLE      # 定位指针到开头
telldir DIRHANDLE        # 返回目录的当前位置
seekdir DIRHANDLE, POS   # 定位指定到目录的 POS 位置
closedir DIRHANDLE       # 关闭目录

All files are displayed

Showing all the files in the directory, the following example uses the glob operator, as shown below:

#!/usr/bin/perl

# 显示 /tmp 目录下的所有文件
$dir = "/tmp/*";
my @files = glob( $dir );

foreach (@files ){
   print $_ . "\n";
}

# 显示 /tmp 目录下所有以 .c 结尾的文件
$dir = "/tmp/*.c";
@files = glob( $dir );

foreach (@files ){
   print $_ . "\n";
}

# 显示所有隐藏文件
$dir = "/tmp/.*";
@files = glob( $dir );
foreach (@files ){
   print $_ . "\n";
}

# 显示 /tmp 和 /home 目录下的所有文件
$dir = "/tmp/* /home/*";
@files = glob( $dir );

foreach (@files ){
   print $_ . "\n";
}

The following examples can list all files in the current directory:

#!/usr/bin/perl

opendir (DIR, '.') or die "无法打开目录, $!";
while ($file = readdir DIR) {
  print "$file\n";
}
closedir DIR;

If you want to display all files in the /tmp directory that end .c , you can use the following code:

#!/usr/bin/perl

opendir(DIR, '.') or die "无法打开目录, $!";
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, and you need to have sufficient permissions to create the directory before executing:

#!/usr/bin/perl

$dir = "/tmp/perl";

# 在 /tmp 目录下创建 perl 目录
mkdir( $dir ) or die "无法创建 $dir 目录, $!";
print "目录创建成功\n";

Delete the directory

We can use the rmdir function to delete the directory, which requires sufficient permissions to do so. Additional directories to be deleted must be empty directories:

#!/usr/bin/perl

$dir = "/tmp/perl";

# 删除 /tmp 目录下的 perl 目录
rmdir( $dir ) or die "无法删除 $dir 目录, $!";
print "目录删除成功\n";

Switch directories

We can use the chdir function to switch the current directory, which requires sufficient permissions to do so. Here's an example:

#!/usr/bin/perl

$dir = "/home";

# 将当期目录移动到 /home 目录下
chdir( $dir ) or die "无法切换目录到 $dir , $!";
print "你现在所在的目录为 $dir\n";

The above procedure is performed and the output is:

你现在所在的目录为 /home