6.3 檔案測試

Perl 對於檔案性質的測試支援非常完整,透過簡單的運算,即可輕鬆掌握檔案的相關資訊。

以下是常用的檔案測試算符:


-r 檔案可讀
-w 檔案可寫入
-x 檔案可執行
-e 檔案/目錄存在
-d 檔案是一個目錄
-s 檔案大小非 0,同時傳回檔案大小
-f 檔案是文字檔
-z 檔案大小為 0
-l 檔案為符號連結檔

用例:

die "$file 這個檔案已經存在了!\n" if -e $file;

用例:

#! /usr/bin/perl

$file="studdemo.csv";

if (-e $file) {
	print "$file 存在!\n";
}

if (-r $file) {
	print "$file 我有讀取權!\n";
}

if (-w $file) {
	print "$file 我有寫入權!\n";
}

if (-x $file) {
	print "$file 我有執行權!\n";
}

# 取得檔案大小
$file_size = -s $file;

print "$file 的檔案大小為:$file_size\n\n";

這裡有完整的檔案測試函式列表:-X.html