Same hash keys, different value: how can I compare them?

Viewed 81

I want to compare the values of the same key in a hashmap. I would like to compare and get the most recent date of the same key. It returns the last date that appears in the hashmap. I want to compare and get the most recent date even if it appears in first in the hashmap. When the same key appears a second time in a hashmap, I'm struggling to compare the second date to the first date when the key appears.

Here is my code :

use strict;
use warnings;
my %hash = ( 48487 => '05/05/19', 
             52327 => '05/05/23', 
               123 => '06/01/01',
             52327 => '07/08/24',
               123 => '07/08/02',
             44147 => '24/12/18',
             48487 => '05/05/18',
             44147 => '24/12/19',
             64998 => '05/11/25',
             52327 => '05/06/24',
             64998 => '05/05/24' );
                    
foreach ( sort { $hash{$a} cmp $hash{$b} } keys %hash) {
    print "Date:$hash{$_}\tKey:$_\n";
}
1 Answers

You think your hash has 11 key/value pairs, but it only has 5 pairs. You can prove this to yourself with: use Data::Dumper; print Dumper(\%hash);

You could use a Hash-of-Arrays data structure instead, then use Time::Piece to compare your 2 dates. Time::Piece is a Core module, which means you should not have to install it.

use warnings;
use strict;
use Time::Piece;

my %hash = (
    48487 => [qw(05/05/19 05/05/18)],
    52327 => [qw(05/05/23 07/08/24)],
      123 => [qw(06/01/01 07/08/02)],
);

for my $k (keys %hash) {
    my $d1 = Time::Piece->strptime($hash{$k}[0], '%d/%m/%y');
    my $d2 = Time::Piece->strptime($hash{$k}[1], '%d/%m/%y');
    if ($d1 > $d2) {
        print "$k $hash{$k}[0]\n";
    }
    else {
        print "$k $hash{$k}[1]\n";
    }
}

This prints:

48487 05/05/19
52327 07/08/24
123 07/08/02

Note: I only posted 3 of your 5 unique keys for simplicity.

Related