傳回由 opendir
開啟目錄的下一筆目錄項目。如果在清單內容中使用,則傳回目錄中所有其餘的項目。如果沒有更多項目,則在純量內容中傳回未定義值,在清單內容中傳回空清單。
如果您計畫對 readdir
的傳回值進行檔案測試,最好在前面加上有問題的目錄。否則,由於我們沒有在那裡 chdir
,它將測試錯誤的檔案。
opendir(my $dh, $some_dir) || die "Can't opendir $some_dir: $!";
my @dots = grep { /^\./ && -f "$some_dir/$_" } readdir($dh);
closedir $dh;
從 Perl 5.12 開始,您可以在 while
迴圈中使用空白 readdir
,這會在每次反覆運算中設定 $_
。如果將 readdir
表達式或將 readdir
表達式明確指定給純量的 while
/for
條件,則該條件實際上會測試表達式值的已定義性,而不是其常規真值。
opendir(my $dh, $some_dir) || die "Can't open $some_dir: $!";
while (readdir $dh) {
print "$some_dir/$_\n";
}
closedir $dh;
為了避免讓使用較早版本 Perl 的程式碼潛在使用者感到困惑,請將此類內容放在檔案頂端,以表示您的程式碼僅適用於近期版本的 Perl
use v5.12; # so readdir assigns to $_ in a lone while test