Latest web development tutorials

Perl directory operations

The following lists some of the standard function operation directory:

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

Show all files

All files are displayed directory, the following example uses glob operator to demonstrate the following:

#!/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 ending in .c / tmp directory, 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 themkdir function to create a new directory, you need to perform before have sufficient permissions to create the directory:

#!/usr/bin/perl

$dir = "/tmp/perl";

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

Remove directory

We can use thermdir function to delete a directory, perform the operation requires sufficient permissions.Also you want to delete directory must empty directory:

#!/usr/bin/perl

$dir = "/tmp/perl";

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

Change directory

We can use thechdir function to switch the current directory, perform the operation requires sufficient permissions.Examples are as follows:

#!/usr/bin/perl

$dir = "/home";

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

The above program, the output is:

你现在所在的目录为 /home