LearningCpp - 1 month ago 4x
Perl Question

# Compare two hash of arrays

I have two arrays and a hash holds these arrays

`````` Array 1:
my \$group = "west"
@{ \$my_big_hash{\$group} } = (1534,2341,2322,3345,689,3333,4444,5533,3334,5666,6676,3435);

Array 2 :

my \$element = "Location" ;
my \$group  = "west" ;
@{ \$my_tiny_hash{\$element}{\$group} } =  (153,333,667,343);
``````

Now i would want to compare

@{ \$my_tiny_hash{\$element}{\$group} }

with

@{ \$my_big_hash{\$group} }

and check whether all the elements of tiny hash array are a part of big_hash array .
As we can see tiny hash has just 3 digit elemnts and the first three diigits are matching with big hash

if first 3 digits/letters match and all are available in the big array, then its matching or We have to print the unmatched elemets

Its an array to array comparision .
How do we acheive it.

PS : Without Array Utils , How to acheive it

The solution using Array Utils is really simple

``````my @minus = array_minus( @{ \$my_tiny_hash{\$element}{\$group} } , @{ \$my_big_hash{\$group} }  );
``````

But it compares all the digits and i would just want to match the first 3 digits

Hope this is clear

Thanks

This seems to do what you want.

``````#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

my (%big_hash, %tiny_hash);
my \$group = 'west';
my \$element = 'Location';

# Less confusing initialisation!
\$big_hash{\$group} = [1534,2341,2322,3345,689,3333,4444,5533,3334,5666,6676,3435];
\$tiny_hash{\$element}{\$group} = [153,333,667,343];

# Create a hash where the keys are the first three digits of the numbers
# in the big array. Doesn't matter what the values are.
my %check_hash = map { substr(\$_, 0, 3) => 1 } @{ \$big_hash{\$group} };

# grep the small array by checking the elements' existence in %check_hash
my @missing = grep { ! exists \$check_hash{\$_} } @{ \$tiny_hash{\$element}{\$group} };

say "Missing items: @missing";
``````

Update: Another solution that seems closer to your original code.

``````my @truncated_big_array = map { substr(\$_, 0, 3) } @{ \$big_hash{\$group} };
my @minus = array_minus( @{ \$my_tiny_hash{\$element}{\$group} } , @truncated_big_array );
``````
Source (Stackoverflow)