Perl学习笔记(2)
在本章中將要學習:(1)如何獲得目錄列表 (2)如何創建和刪除文件 (3)如何創建和刪除目錄 (4)如何獲取關于文件的信息。
一、獲得目錄列表
目錄句柄與文件句柄的不同之處是:文件是通過讀取文件句柄獲得文件的內容,而目錄是通過使用目錄句柄來讀取目錄的內容。
opendir? dirhandle?,directory
在上面這個語句,dirhandle是要打開的目錄句柄,directory是要讀取目錄的內容。
opendir(TEMPDIR, '/tmp') || die "Cannot open directory"
readdir? dirhandle;
目錄句柄打開后,可以使用readdir函數來讀取它的內容。
closedir? dirhandle;
當完成目錄句柄的操作后,應該使用closedir函數將它關閉。
opendir(TEMP,'/tmp') || die "Cannot open /tmp: $!\n";
@FILES=readdir TEMP;
closedir(TEMP);
在上面這個代碼中,整個目錄被讀取@FILES中。
@FILES=grep(!/^\.\.?$/, readdir TEMP);
排除 .? 和 ..
若要獲得帶有特定擴展名的全部文件,可以使用下面代碼
@FILES=grep(/\.txt$/i, readdir TEMP);
readdir返回的文件名并不包含opendir使用的路徑名。因此以下代碼可能有問題
opendir(TD, '/tmp') || die "Cannot open /tmp: $!\n";
while($file=readdir TD) {
?????? open(FILEH, $file) || die "Cannot open $file: $!\n";
}
closedir(TD);
正確的代碼應該改成 open(FILEH,'/tmp/$file')
?==========================================
二、Globbing
讀取目錄中的文件名的另一種方法是使用globbing
glob的模式與正則表達式的模式不同
???????? 單個字符???????? f?d????? fud fad
*??????? 任何數據的字符??? f*d? fod food
[chars]?? 用于匹配任何一個chars??? f[ou]d??? fod? fud
{a.b,.....}? 既可以匹配字符串a,也可以匹配b???? f*{txt,doc}用于匹配以f開頭的,以txt或doc結尾的文件。
@a=glob('/tmp/*');
print "@a\n";?????????????????? 返回/tmp/a?? /tmp/b?? 顯示目錄名和文件名,而readdir不能。
@file=glob('/usr/include/*.h');
@curfiles=glob('*1999*.{txt,doc}')
$count=1;
while($name=glob('*')) {??????????????? 讀取當前目錄下的所有文件和目錄
??????? print "$count . $name\n";
??????? $count++;
}
下面是使用glob與opendir/readdir/closedir之間的差別;
glob只能返回有限數量的文件,而readdir則不存在這個問題。
glob返回模式中使用的路徑名,而readdir則不能。
perl提供另外一種方法,用于編寫模式glob。 只需要將模式放入<>中。
@a=<*.c>
?
chkdir? newdir;?? chdir函數將當前工作目錄改為newdir。chdir對目錄的改變時暫時的,一旦perl程序執行完畢,就返回之前的目錄。
?
=========================================
三、創建和刪除目錄
print? "Directory to create?";
my? $newdir=<STDIN>;
chomp $newdir;
mkdir( $newdr, 0755) || die "Failed to create $newfile: $!\n";
rmdir? pathname? 可以刪除目錄
rmdir($newdir);
rmdir函數只刪除完全是空的目錄。
=====================================
四、刪除文件
unlink? list_of_files;
unlink? @badfiles;
$erased=unlink 'old.exe' , 'a.out';
unlink?;
若要檢查文件列表是否已被刪除,必須對想要刪除的文件數量與已刪除的文件數量進行比較。
@files=<*.txt>;
@erased=unlink @files;
if ($erased != @files) {
???? print "Files failed to erase: ";
???? join(',' , <*.txt>),"\n";
}
在上面這個代碼中,被unlink刪除的文件數量存放在$erased中。
?=====================================
五、給文件改名
rename? oldname, newname;
if (! rename "myfile.txt", "archive.txt") {
???? warn "Could not rename myfile.txt:? $!";
}
======================================
六、了解文件的所有信息
可以使用perl的stat函數
@stuff=stat('file');
($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,
$mtime,$ctime,$blksize,$blocks)=stat('outfile')
轉載于:https://blog.51cto.com/2614223/910975
總結
以上是生活随笔為你收集整理的Perl学习笔记(2)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: String 常量池
- 下一篇: Hibernate 一对一外键单向关联