比较经典的一种对比文件的方式。。看了这段代码有点感悟。
但没有写出来,回头整理看看。。
#! /usr/bin/perl use strict; use warnings; my $src_lines_1_ref = get_lines_from_file('1.txt'); my $src_lines_2_ref = get_lines_from_file('2.txt'); my @dst_lines = grep { my $line = $_; grep $_ eq $line, @$src_lines_1_ref; } @$src_lines_2_ref; write_lines_to_file('3.txt', \@dst_lines); sub get_lines_from_file { my $file = shift || ""; my @lines; open my $FILE, "<$file" or die "Cannot open $file: $!"; while (<$FILE>) { chomp; next if /^\s*$/ #删除空行 s/^\s*//; # 注释掉行头的空格 s/\s*$//; # 注释掉行尾的空格 push @lines, $_; } close $FILE; return \@lines; } sub write_lines_to_file { my $file = shift || ""; my $lines_ref = shift || ""; open my $FILE, ">$file" or die "Cannot open $file: $!"; for (@$lines_ref) { print $FILE $_."\n"; } close $FILE; }