今天是perl系統管理腳本的第二課,内容和第一課差不多,不過第二課是對第一課有了進一步深入的使用,如将功能內建化,還有實作了遞歸調用........大家可以模仿這個做類似的腳本.......
#*
#* scans a filesystem "by hand" for core files with optional deletion
#!/usr/bin/perl -s
# note the use of -s for switch processing. Under NT/2000, you will need
# call this script explicitly with -s (i.e. perl -s script) if you do not
# have perl file associations in place.
#
# -s is also considered 'retro', many programmers preferring to load
# a separate module (from the Getopt:: family) for switch parsing.
use Cwd; # module for finding the current working directory
# This subroutine takes the name of a directory and recursively scans
# down the filesystem from that point looking for files named "core"
sub ScanDirectory{ #目錄掃描函數
my ($workdir) = shift; #儲存函數傳遞的參數
my ($startdir) = &cwd; # keep track of where we began #記錄目前工作目錄
chdir($workdir) or die "Unable to enter dir $workdir:$!\n"; #轉到掃描目錄下
opendir(DIR, ".") or die "Unable to open $workdir:$!\n"; #打開目錄句柄
my @names = readdir(DIR) or die "Unable to read $workdir:$!\n"; #将目錄下的内容指派給數組
closedir(DIR);
foreach my $name (@names){
next if ($name eq ".");
next if ($name eq "..");
if (-d $name){ # is this a directory?
&ScanDirectory($name); #再次調用這個函數
next;
}
if ($name eq "core") { # is this a file named "core"?
# if -r specified on command line, actually delete the file
if (defined $r){
unlink($name) or die "Unable to delete $name:$!\n";
}
else {
print "found one in $workdir\n";
}
chdir($startdir) or die "Unable to change to dir $startdir:$!\n";
}
&ScanDirectory(".");
[學習]
這課有個特色就是循環的讀取某個指定目錄,直到在指定的目錄下沒有目錄了.一次又一次的将與指定的文
件進行比對.在這裡,我們看到了,将某一個功能內建化,就是把目錄掃描檔案的功能寫到一個函數了,在借助CWD模
塊,記錄目前工作目錄,以實作遞歸的查找檔案,當符合條件時,采取一定的動作,如删除.......
本文轉自hahazhu0634 51CTO部落格,原文連結:http://blog.51cto.com/5ydycm/115388,如需轉載請自行聯系原作者