blueice 发表于 2018-9-1 10:00:56

跟我一起学 第1课

opendir(DIR,".") or die "Can't open the current directory: $!\n";  # read file/directory names in that directory into @names
  @names = readdir(DIR) or die "Unable to read current dir:$!\n";
  closedir(DIR);
  foreach $name (@names) {
  next if ($name eq "."); # skip the current directory entry
  next if ($name eq ".."); # skip the parent directory entry
  if (-d $name){ # is this a directory?
  print "found a directory: $name\n";
  next; # can skip to the next name in the for loop
  }
  if ($name eq "core") { # is this a file named "core"?
  print "found one!\n";
  }
  }
  [学习]
  这个脚本的作用是用来在当前的目录下查找core文件的,类似与bash下的find
  find . -type f -name "core"
  这个脚本在功能上看上去很简单,就是一个查找的功能,但我们可以将其扩展为一个函数,用与以后我们在写大一点的脚本时,将其作为一个查找的功能.最起码,我们在这里可以学习目录句柄嘛,像opendir(DIR,"."),大家经常写的其实是文件句柄如open(FIN,"/etc/passwd"),还有像循环语句foreach.....还有字各个地方串比较符eq,这些都是小的细节,都是我们在脱离书本时,是否能够想得到呢?我想未必吧,至少我有时也会忘记,哈哈(我是perl的初学者哟)!
  [扩展]
  #!/usr/bin/perl -w
  #Author:badboy
  #2008/11/25 13:30
  $file = file.lock;
  $tmp=/tmp;
  opendir(DIR,"$tmp") or die "Can't open the current directory: $!\n";
  @names = readdir(DIR) or die "Unable to read current dir:$!\n";
  closedir(DIR);
  foreach $name (@names) {
  next if ($name eq ".");
  next if ($name eq "..");
  if (-d $name){
  next;
  }
  if ($name eq $file) {
  Sendmail $name; #将其名称传递给Sendmail函数
  }
  }
  这个扩展脚本是用与临时解决问题的功能,假设我们应用出现一个这样的问题,只要在/tmp目录下出现file.lock,应用将不能使用,而我们此时又找不到根源,这时我们就可以用这个借助cron定时的检查这个文件,一出现就发邮件通知给你,让你在第一时间处理.还可以用在很多地方,还需要大家活用,我这种用法只是解决临时性的,解决问题才是关键......

页: [1]
查看完整版本: 跟我一起学 第1课