Perl 简明教程
Perl - Directories
下面是用于处理目录的标准函数。
opendir DIRHANDLE, EXPR # To open a directory
readdir DIRHANDLE # To read a directory
rewinddir DIRHANDLE # Positioning pointer to the begining
telldir DIRHANDLE # Returns current position of the dir
seekdir DIRHANDLE, POS # Pointing pointer to POS inside dir
closedir DIRHANDLE # Closing a directory.
Display all the Files
有各种方法可以列出特定目录中所有可用的文件。首先,我们使用简单的方法,即使用 glob 运算符获取并列出所有文件 −
#!/usr/bin/perl
# Display all the files in /tmp directory.
$dir = "/tmp/*";
my @files = glob( $dir );
foreach (@files ) {
print $_ . "\n";
}
# Display all the C source files in /tmp directory.
$dir = "/tmp/*.c";
@files = glob( $dir );
foreach (@files ) {
print $_ . "\n";
}
# Display all the hidden files.
$dir = "/tmp/.*";
@files = glob( $dir );
foreach (@files ) {
print $_ . "\n";
}
# Display all the files from /tmp and /home directories.
$dir = "/tmp/* /home/*";
@files = glob( $dir );
foreach (@files ) {
print $_ . "\n";
}
这里有另一个示例,它打开了一个目录,并列出此目录中所有可用的文件。
#!/usr/bin/perl
opendir (DIR, '.') or die "Couldn't open directory, $!";
while ($file = readdir DIR) {
print "$file\n";
}
closedir DIR;
可以用来打印 C 源文件列表的另一个示例是 −
#!/usr/bin/perl
opendir(DIR, '.') or die "Couldn't open directory, $!";
foreach (sort grep(/^.*\.c$/,readdir(DIR))) {
print "$_\n";
}
closedir DIR;
Create new Directory
您可以使用 mkdir 函数创建一个新目录。您需要具有创建目录的必需权限。
#!/usr/bin/perl
$dir = "/tmp/perl";
# This creates perl directory in /tmp directory.
mkdir( $dir ) or die "Couldn't create $dir directory, $!";
print "Directory created successfully\n";