I have two hashes and I want to iterate over the first hashes keys once (tcp, tls, dns) and then find the matching key in the second hash. From there I want to compare the values in each hash for tcp.
At the moment when I attempt to do this, it seems to match on every key in the second hash. TCP may be selected from the first hash but where I have if ($key1 == $key2), it will match multiple times even though the keys do not match each other. It may be me not having a proper understanding of each.
#!/usr/bin/perl
open my $fh, "newlogs.txt" or die $!;
my %line_1 = split ' ', <$fh>;
my %line_2 = split ' ', <$fh>;
while (my($key1, $value1) = each %line_1) {
while (my($key2, $value2) = each %line_2) {
if ($key1 == $key2) {
print "$key1 $key2\n";
}
}
}
newlog.txt:
tcp 217837 tls 138531 http 50302 udp 37852 dns 23625 ldap 14160 krb5 8828 smb 2148 ssh 549 ftp 219 smtp 161 icmp 6 rdp 3 ssdp 3
tcp 198650 tls 125770 http 44260 udp 37610 dns 23827 ldap 13904 krb5 8805 smb 2128 ssh 629 ftp 219 smtp 156 icmp 5 ssdp 1
I'd hope to achieve something like this for the output which shows the difference in both tcp values, but for every protocol (key). tcp=19187
EDIT:
I've found a solution here: Comparing two hashes with the keys and values
Solution:
#!/usr/bin/perl
open my $fh, "newlogs.txt" or die $!;
my %line_1 = split ' ', <$fh>;
my %line_2 = split ' ', <$fh>;
for (keys %line_1) {
unless (exists $line_2{$_} ){
print "$_: not found in second hash\n";
next;
}
if ($line_1{$_} eq $line_2{$_} ) {
print "$_: no change \n";
}
else {
#print "$_: values are not equal\n";
my $result = $line_1{$_} - $line_2{$_};
print "$result\n";
}
}
unlessblock) then you are missing cases when a key in%line_2is not in%line_1. But it seems that you rather don't care about that and may do away withunlessblock.) - zdimeachindeed can be a little tricky ... but I am not sure what is wrong there, your attempt is reasonable. - zdimuse warnings;anduse strict;at the beginning. It really helps a lot. - zdim