我想獲得一個目錄的詳細信息,就像其中的文件和子目錄的數量以及這些目錄的權限。如何使用perl腳本獲取目錄的屬性?
是的!在linux機器上使用back tick執行命令很容易。但是有沒有辦法讓腳本平臺獨立。
謝謝:)
我想獲得一個目錄的詳細信息,就像其中的文件和子目錄的數量以及這些目錄的權限。如何使用perl腳本獲取目錄的屬性?
是的!在linux機器上使用back tick執行命令很容易。但是有沒有辦法讓腳本平臺獨立。
謝謝:)
您可以使用目錄句柄(opendir和readdir)來獲得目錄的內容和File::stat得到你可能要考慮使用Path::Class權限
。這既爲您提供了一個簡單的界面,同時也爲您處理所有跨平臺事宜(包括平臺上的「\」和「/」之間的區別)。
use Path::Class qw(file dir);
my $dir = dir("/etc");
my $dir_count = 0;
my $file_count = 0;
while (my $file = $dir->next) {
# $file is a Path::Class::File or Path::Class::Dir object
if ($file->is_dir) {
$dir_count++;
} else {
$file_count++;
}
my $mode = $file->stat->mode;
$mode = sprintf '%o', $mode; # convert to octal "0755" form
print "Found $file, with mode $mode\n";
}
print "Found $dir_count dirs and $file_count files\n";
如果您無法統計文件,該怎麼辦?然後undef->模式將不起作用......但您已經將其計入$ file_count中。 – oylenshpeegul 2010-08-05 12:10:00
@oslenshpeegul:什麼情況下我會無法統計文件?我剛剛成功閱讀了目錄中的內容...... – 2010-08-30 09:43:00
這是一個很好的解決方案(不同於我的Path :: Class示例),您只需要使用隨Perl本身分發的核心模塊。 – 2010-08-05 10:59:08