我正在尝试编写一个脚本,该脚本接收一个文件并将其与第二个文件进行比较,然后输出差异。我有它的工作,但我决定要摆脱任何以#开头的行。我不得不使用push as。=不能正常工作。从那以后我得到像
这样的输出keys = GLOB(0x23d2d48)
我不确定我错过了什么。
#!/usr/bin/perl
use warnings;
use lib '/var/www/oooOOoO/lib/Perl';
my @a1;
my @a2;
my %diff1;
my %diff2;
my @diff1;
my @diff2;
my $input_file = "/etc/mysql/conf.d/replication-slave.cnf";
my $input_file2 = "tA.cnf";
open( my $input_fh, "<", $input_file ) || die "Can't open $input_file: $!";
open( my $input_fh2, "<", $input_file2 ) || die "Can't open $input_file: $!";
@a1 = ' ';
for ($input_fh) {
next if /^#/;
push@a1, $_;
}
@a2= ' ';
for ($input_fh2) {
next if /^#/;
push @a2, $_;
}
@diff1{ @a1 } = @a1;
delete @diff1{ @a2 };
# %diff1 contains elements from '@a1' that are not in '@a2'
@k = (keys %diff1);
print "keys = @k\n";
我尝试将键更改为值,但这不起作用。
由于
答案 0 :(得分:2)
问题在于这段代码:
for ($input_fh) {
next if /^#/;
push @a1, $_;
}
这是创建一个包含文件句柄的单个元素列表,然后将该文件句柄推送到@a1
。要从文件句柄中读取,您需要使用<>
包装它:
while (<$input_fh>) {
next if /^#/;
push @a1, $_;
}
注意我已将for
切换为while
for
强制列表上下文并一次性读取所有文件,而while
将读取一行一时间您也可以删除:
@a1 = ' ';
@a2 = ' ';
这只是为两个数组添加了一个额外的元素。
答案 1 :(得分:1)
加载两个阵列后,最好使用Perl CPAN模块来执行此类控制。我认为Array::Utils是实现目标的好选择。从模块文档:
use Array::Utils qw(:all);
my @a = qw( a b c d );
my @b = qw( c d e f );
# symmetric difference
my @diff = array_diff(@a, @b);
# intersection
my @isect = intersect(@a, @b);
# unique union
my @unique = unique(@a, @b);
# check if arrays contain same members
if ( !array_diff(@a, @b) ) {
# do something
}
# get items from array @a that are not in array @b
my @minus = array_minus( @a, @b );
答案 2 :(得分:1)
它应该可以工作,但你的代码有点乱。当您指定@diff1{@a1} = @a1
时,我也不确定您要做什么。
尝试重写并告诉我:
#!/usr/bin/perl
use strict;
use warnings;
use lib '/var/www/ooooOOooOoo/lib/Perl';
my $input_file = "/etc/mysql/conf.d/replication-slave.cnf";
my $input_file2 = "tA.cnf";
open my $input_fh, "<", $input_file or die "Can't open $input_file: $!";
open my $input_fh2, "<", $input_file2 or die "Can't open $input_file: $!";
my (@a1, @a2);
while(<$input_fh>){
chomp;
next if /^#/;
push @a1, $_;
}
while(<$input_fh2>){
chomp;
next if /^#/;
push @a2, $_;
}
my %diff1;
@diff1{@a1} = @a1; # What are you actually trying to do here?
delete @diff1{@a2};
# %diff1 contains elements from '@a1' that are not in '@a2'
my @k = (keys %diff1);
print "keys = @k\n";
但你可能想尝试这种方法:
my @nums1 = qw(1 2 3 4 5);
my @nums2 = qw(one two three four 5);
my (%compare1, %compare2);
foreach(@nums1){
chomp;
$compare1{$_} = 1;
}
foreach(@nums2){
chomp;
$compare2{$_} = 1;
}
foreach my $key (keys %compare1){
print "$key\n" unless $compare2{$key};
}