aboutsummaryrefslogtreecommitdiff
path: root/challenge-132/mohammad-anwar/perl/ch-2.pl
blob: 36f1959af90b22f04e4c4a70531bc4183980c30f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#!/usr/bin/perl

=head1

Week 132:

    https://theweeklychallenge.org/blog/perl-weekly-challenge-132

Task #2: Hash Join

    Write a script to implement Hash Join algorithm as suggested by wikipedia.

=cut

use strict;
use warnings;

my @player_ages = (
    [20, "Alex"  ],
    [28, "Joe"   ],
    [38, "Mike"  ],
    [18, "Alex"  ],
    [25, "David" ],
    [18, "Simon" ],
);

my @player_names = (
    ["Alex", "Stewart"],
    ["Joe",  "Root"   ],
    ["Mike", "Gatting"],
    ["Joe",  "Blog"   ],
    ["Alex", "Jones"  ],
    ["Simon","Duane"  ],
);

hash_join(\@player_ages, 1, \@player_names, 0);

sub hash_join {
    my ($table_1, $key_1, $table_2, $key_2) = @_;

    my $names = {
        map {
            join(", ", @$_) => $_->[$key_2]
        } @$table_2
    };

    foreach my $player (@$table_1) {
        my $key = $player->[$key_1];
        my $age = $player->[0];
        foreach my $n (keys %$names) {
            if ($names->{$n} eq $key) {
                print "$age, $n\n";
            }
        }
    }
}