我有两个从IntexCalc和Intex API生成的文件,我想比较它们的内容。我不想逐行比较。下面的示例将提供有关它的更多详细信息。
文件 1
LOSS_UNITS["GRPY"]==CDR
LOSS_USERCURVE_TYPE["GRPY"]==PCT_MULTIPLY
LOSS_USERCURVE_INDEX_OFFSET["GRPY"]==BY_LOAN_AGE
LOSS_RATE["GRPY"]==100
LOSS_NONPERF_ADV_PCT_P["GRPY"]==0
LOSS_NONPERF_ADV_PCT_I["GRPY"]==0
SEVERITY_USERCURVE_TYPE["GRPY"]==NONE
文件 2
LOSS_USERCURVE_TYPE["GRPY"]=PCT_MULTIPLY
LOSS_NONPERF_ADV_PCT_P["GRPY"]=0
LOSS_UNITS["GRPY"]=CDR
LOSS_NONPERF_ADV_PCT_I["GRPY"]=0
SEVERITY_USERCURVE_TYPE["GRPY"]=NONE
LOSS_SEVERITY["GRPY"]=31.73
LOSS_USERCURVE_INDEX_OFFSET["GRPY"]=BY_DEAL_AGE
我想比较两个文件中的
LOSS_UNITS["GRPY"]
标志值。在这两个文件中,无论它们在文件中的位置如何,它们在 =/== 之后的值都是相同的,因此此标志值相等。文件 1 中
LOSS_USERCURVE_INDEX_OFFSET["GRPY"]
的标志值为BY_LOAN_AGE
,文件 2 中的标志值为BY_DEAL_AGE
,因此此标志值不同。标志
LOSS_RATE["GRPY"]
仅存在于文件 1 中,因此这是区别标志
LOSS_SEVERITY["GRPY"]
仅存在于文件 2 中,因此这也是一个区别。
比较这种文件结构的最佳方法或工具是什么?
我建议你使用Data::Diff
模块
它返回对包含参数之间差异摘要的哈希的引用。关键是
-
same
— 两种情况下相同的元素 -
diff
— 给定键具有不同值的元素 -
uniq_a
和uniq_b
— 仅出现在一个结构或另一个结构中的元素
use strict;
use warnings 'all';
use autodie;
use Data::Dump;
use Data::Diff 'Diff';
my %f1 = do {
open my $fh, '<', 'file1.txt';
map { s/s+z//; split /=+/, $_, 2 } <$fh>;
};
my %f2 = do {
open my $fh, '<', 'file2.txt';
map { s/s+z//; split /=+/, $_, 2 } <$fh>;
};
my $diff = Diff((%f1, %f2));
dd $diff;
输出
{
diff => {
"LOSS_USERCURVE_INDEX_OFFSET[\"GRPY\"]" => { diff_a => "BY_LOAN_AGE", diff_b => "BY_DEAL_AGE", type => "" },
},
same => {
"LOSS_NONPERF_ADV_PCT_I[\"GRPY\"]" => { same => 0, type => "" },
"LOSS_NONPERF_ADV_PCT_P[\"GRPY\"]" => { same => 0, type => "" },
"LOSS_UNITS[\"GRPY\"]" => { same => "CDR", type => "" },
"LOSS_USERCURVE_TYPE[\"GRPY\"]" => { same => "PCT_MULTIPLY", type => "" },
"SEVERITY_USERCURVE_TYPE[\"GRPY\"]" => { same => "NONE", type => "" },
},
type => "HASH",
uniq_a => { "LOSS_RATE[\"GRPY\"]" => 100 },
uniq_b => { "LOSS_SEVERITY[\"GRPY\"]" => 31.73 },
}
一个没有灵感的解决方案:将键和值放入两个哈希中并进行比较。
sub f2h {
my( $hr, $path ) = @_;
open FILE, $path or die "$path: couldn't open: $!";
while( my $line = <FILE> ){
$line =~ s/s+$//; # there are trailing spaces in your data
my( $key, $val ) = split( /==?/, $line );
$hr->{$key} = $val;
}
close FILE;
}
my %h1;
my %h2;
f2h( %h1, "file1.dat" );
f2h( %h2, "file2.dat" );
while( my( $k, $v ) = each %h1 ){
if( exists( $h2{$k} ) ){
print "different $kn" if $h2{$k} ne $v;
} else {
print "$k missing in 2n";
}
}
while( my( $k, $v ) = each %h2 ){
print "$k missing in 1n" unless exists $h1{$k};
}