Kirs Kringle Kirs Kringle - 2 months ago 11
Perl Question

Getting GLOB values instead of file content

I am trying to write a script that takes in one file and compares it to the second and then outputs the difference. I had it working, but decided I wanted to get rid of any line that starts with '#." I had to use push as .= was not working. Ever since then I get output like


keys = GLOB(0x23d2d48)


I'm not sure what I am missing.

#!/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";


I've tried changing keys to values, but that didn't work.

Thanks

Answer

It should work, but you're code's a little messy. I'm also not sure what you're trying to do when you assign @diff1{@a1} = @a1.

Try this re-write and let me know:

#!/usr/bin/perl
use strict;
use warnings;
use lib '/var/www/CaseSentry/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";

But you might want to try this approach instead:

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};
}