今天是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,如需转载请自行联系原作者