andyyuduo 发表于 2015-12-27 10:28:07

Perl: 文件操作、my、时间转换、日志监控

  ①文件操作
  使用Perl从文件中读取字符串,一般有两种方法:
1. 一次性将文件中的所有内容读入一个数组中(该方法适合小文件):




open(FILE,"filename")||die"can not open the file: $!";
@filelist=<FILE>;
foreach $eachline (@filelist) {
      chomp $eachline;
}
close FILE;

  当文件很大时,可能会出现"out of memory"错误,这是可以采用如下方法,一次读取一行。
  2. 一次从文件中读取一行,一行行地读取和处理(读取大文件时比较方便):




open(FILE,"filename")||die"can not open the file: $!";
while (defined ($eachline =<FILE>)) {
   chomp $eachline;
         # do what u want here!
}
close FILE;
  ②our、my、local的区别
  http://www.cppblog.com/converse/archive/2008/07/31/57636.html
  http://topic.csdn.net/t/20000223/18/2737.html
  our:全局变量定义,如果在函数里定义的时候全局已经定义,则相当于引用全局变量;(全部访问:上级,当前,下级)
  local:把全局变量局部化(等于是局部的全局变量);局部化后所有由此局部引出的这个变量的修改,都只影响到该局部为止。(访问:当前,下级)
  my:真正的局部变量,该变量仅在此局部中有效,在子过程中无效。(访问:当前)
  
  ③时间的转换(日常所用的日期和时间串格式 与 纪元秒 之间的转换)
  纪元to日常:$common = localtime(time); # 秒,分,时, 日,月,年,一周第几天,一年第几天,夏令时
  日常to纪元:$epoch_seconds = timelocal($s,$m,$h,$mday,$mon,$year);
  http://muent.com/a/develop/AllDL/201004303575.html
  
  ④日志监控
  模拟写日志:




use IO::Handle;
open (FD, "> test.log") or die $!;
FD->autoflush(1);
while (1) {
    my $now = time;
    print FD $now, "\n";
    sleep 1;
}
close FD;
  模拟监控日志:




open (FD, "< test.log") or die $!;
while (1) {
    my $in = <FD>;
    print $in;
}
close FD;
  小刁提醒:读入时可以写为 "< tail -f test.log |"
  
  ⑤子过程
  http://blog.csdn.net/aldenphy/archive/2009/11/03/4761585.aspx
页: [1]
查看完整版本: Perl: 文件操作、my、时间转换、日志监控