用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;
廣告