Perl directory manipulation
The following lists some standard functions for operating directories:
opendir DIRHANDLE, EXPR # 打开目录 readdir DIRHANDLE # 读取目录 rewinddir DIRHANDLE # 定位指针到开头 telldir DIRHANDLE # 返回目录的当前位置 seekdir DIRHANDLE, POS # 定位指定到目录的 POS 位置 closedir DIRHANDLE # 关闭目录
Display all files
Display all files in the directory. The following example uses the glob operation symbol, the demonstration is as follows:
#!/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 example 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 with .c in the /tmp directory, 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. You need to have sufficient permissions to create the directory before execution. :
#!/usr/bin/perl $dir = "/tmp/perl"; # 在 /tmp 目录下创建 perl 目录 mkdir( $dir ) or die "无法创建 $dir 目录, $!"; print "目录创建成功\n";
Delete directory
We can use the rmdir function to delete the directory. Sufficient permissions are required to perform this operation. In addition, the directory to be deleted must be an empty directory:
#!/usr/bin/perl $dir = "/tmp/perl"; # 删除 /tmp 目录下的 perl 目录 rmdir( $dir ) or die "无法删除 $dir 目录, $!"; print "目录删除成功\n";
Switch directory
We can use the chdir function to switch the current directory. To perform this operation, you need to have enough permissions. The example is as follows:
#!/usr/bin/perl $dir = "/home"; # 将当期目录移动到 /home 目录下 chdir( $dir ) or die "无法切换目录到 $dir , $!"; print "你现在所在的目录为 $dir\n";
Execute the above program, the output result is:
你现在所在的目录为 /home