为了更好地利用Perl,下面为实现对xxx.log的日志,检查当中是否存在fail的字段的目的,逐段给出代码,然后分析
实验材料
- xxx.log日志文件
- check_fail.pl脚本
读取文件
# check_fail.pl
$value;
$value = open(file, "< xxx.log"); # 利用open函数打开xxx.log脚本,并指向file句柄, $value用于指示open的执行情况
if(!$value){
print("open xxx.log failed\n");
} else {
print("open xxx.log successfully\n");
}
文本处理
while(<file>){ # 遍历文件的每一行,同时打印出来,如果match到了fail, 就打印相关信息和当前行
print($_);
print("\n");
if( $_ =~ m/fail/) {
print("match: find $&\n");
}
}
关闭文件
close file;
总结加迁移
- 使用open函数打开文件,利用句柄指向文件,最后记得用close关闭文件
- $& 表示上一次匹配成功的字符
- =,!分别表示字符匹配,不匹配
- 待匹配字符的表示m/str/
- 文件操作时,用 <,>, > > 表示数据流向.(<读取, > 写入, > >追加)