我正在使用两个文本文件sampleA.txt和sampleB.txt。我在每个文件中都有两个字段,我需要将sampleA.txt的第一条记录(第一行)与sampleB.txt的第一行进行比较,我想在命令提示符下显示匹配的记录以及未匹配的记录。在Perl中做到这一点。
使用以下脚本,我得到一个输出,但这是错误的。我需要同时填充匹配和不匹配。怎么做?
sampleA.txt:
1|X
2|A
4|Z
5|A
sampleB.txt:
2|A
2|X
3|B
4|C
我得到的输出:
2|A
2|X
4|C
我想要的输出:
匹配输出:
2|A
错配输出:
1|X
4|Z
5|A
3|B
4|C
Perl脚本:
#!/usr/bin/perl
use strict;
use warnings;
open(FILE1,'C:\Users\sathiya.kumar\Desktop\sampleA.txt') || die $!;
open(FILE2,'C:\Users\sathiya.kumar\Desktop\sampleB.txt') || die $!;
my $interline;
while (my $line= <FILE1>) {
my @fields = split('\|',$line);
parser($fields[0]);
}
sub parser {
my $mergeid = shift;
while (defined $interline || ($interline= <FILE2>)) {
my @fields = split('\|',$interline);
my $key = $fields[0];
if ($key lt $mergeid) {
# Skip non-matching records
$interline = undef;
next;
} elsif ($key gt $mergeid) {
# wait for next key
last;
} else {
print $interline;
$interline = undef;
}
}
}
close(FILE1);
close(FILE2);
如果您需要更多信息,请与我们联系。
您没有列出2|X
:
use strict;
use warnings;
use 5.016;
use Data::Dumper;
#Create a set from the entries in sampleA.txt:
my $fname = 'sampleA.txt';
open my $A_INFILE, '<', $fname
or die "Couldn't open $fname: $!";
my %a;
while (my $line = <$A_INFILE>) {
chomp $line;
$a{$line} = undef;
}
close $A_INFILE;
say Dumper(\%a);
#Create a set from the entries in sampleB.txt:
$fname = 'sampleB.txt';
open my $B_INFILE, '<', $fname
or die "Couldn't open $fname: $!";
my %b;
while (my $line = <$B_INFILE>) {
chomp $line;
$b{$line} = undef;
}
close $B_INFILE;
say Dumper(\%b);
#Divide the entries in both files into matches and mismatches:
my (@matches, @mismatches);
for my $a_val (keys %a) {
if (exists $b{$a_val}) {
push @matches, $a_val;
}
else {
push @mismatches, $a_val;
}
}
for my $b_val (keys %b) {
if (not exists $a{$b_val}) {
push @mismatches, $b_val;
}
}
say Dumper(\@matches);
say Dumper(\@mismatches);
--output:--
$VAR1 = {
'5|A' => undef,
'4|Z' => undef,
'1|X' => undef,
'2|A' => undef
};
$VAR1 = {
'2|X' => undef,
'3|B' => undef,
'4|C' => undef,
'2|A' => undef
};
$VAR1 = [
'2|A'
];
$VAR1 = [
'5|A',
'4|Z',
'1|X',
'2|X',
'3|B',
'4|C'
];
如果在标量上下文中评估哈希,则如果哈希为空,则返回false。如果有任何键/值对,则返回true;否则,返回true。更确切地说,返回的值是一个字符串,该字符串由使用的存储桶数和分配的存储桶数组成,并用斜杠分隔。这仅在发现Perl的内部哈希算法在数据集上是否表现不佳时非常有用。例如,您将10,000个东西粘贴在一个散列中,但是在标量上下文中评估%HASH会显示“ 1/16”,这意味着仅触摸了16个存储桶中的一个,大概包含了所有10,000个项。这是不应该发生的。如果在标量上下文中计算绑定哈希,则将调用SCALAR方法(回退到FIRSTKEY)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句