Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl, comparing hashes, sub set

Tags:

hash

perl

subset

I was wondering if there is any easy algorithms to compare to see if one hash is a subset of another hash.

For example, if

$HASH{A} = B;
$HASH{B} = C;
$HASH{C} = D;

$HASH2{A} = B;
$HASH2{B} = C;

then %HASH2 is a subset of %HASH.

like image 683
Gordon Avatar asked Jan 01 '26 05:01

Gordon


1 Answers

This uses "smart matching" (~~) and List::Util::first

use 5.010;
use List::Util qw<first>;

sub hash_is_subset { 
    my ( $hash, $cand ) = @_;
    return not defined( first { not $hash->{ $_ } ~~ $cand->{ $_ } } keys %$cand );
}

hash_is_subset( \%HASH, \%HASH2 );
like image 150
Axeman Avatar answered Jan 05 '26 00:01

Axeman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!