显示Perl中的所有文件
有多种方法可以使用Perl列出特定目录中的所有可用文件。首先,让我们使用简单的方法通过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;