Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Checking contents of array against contents of a hash

by Marshall (Canon)
on Oct 07, 2010 at 20:50 UTC ( #864086=note: print w/replies, xml ) Need Help??


in reply to Checking contents of array against contents of a hash

Another approach is shown below. Basically you are trying to find out if the @all array is a subset of each of the dlist arrays. I assumed that perhaps the dlist array might contain more e-mail addresses than the @all array.

This type of "check off the list" comparison is often done with hash tables. My comparison function makes a hash out of the dlist from the HoA. Then it iterates over each e-mail in @all and "checks off" in the hash as each one is "seen". If I find a e-mail address from the @all list that isn't in the array from the dlist hash, then it can't be a subset and the function returns a failure (not a subset).

Once it has been determined that the dlist (like "listC") contains all of the e-mail addresses in all, I count up any "extra" ones and return that list. This would allow say the compression of "listC" to be "all@foo.com, billy@foo.com".

A noteworthy point here is how returning the @extra array was handled. I return () to mean "nothing", NOT undef. undef is a value. Returning () means "nothing" which is "less than" returning an undef value. The first time I did this, it took me many hours to figure out how to do it! So at some point in the future just having seen this one point may save you a lot of grief! Have fun...

#!/usr/bin/perl -w use strict; use Data::Dumper; my@all = qw(bob@foo.com joe@foo.com jane@foo.com); my %dlists = ( 'listA' =>[ qw (bob@foo.com jane@foo.com joe@foo.com) ], 'listB' =>[ qw (bob@foo.com)], 'listC' =>[ qw (bob@foo.com joe@foo.com jane@foo.com billy@foo.com)], ); foreach my $dlist (keys %dlists) { my ($subset, @extra) = is_array_subset(\@all, \@{$dlists{$dlist}}); if ($subset) { print "$dlist contains all users "; if (@extra) { print "and ".@extra." additional addresses\n"; } else { print "\n"; } } } sub is_array_subset #returns (yes|no status, @extra) { my ($ref_all, $ref_dlist) = @_; my %dlist = map{$_ => 0 }@$ref_dlist; foreach (@$ref_all) { return (0, ()) if !exists($dlist{$_}); #give up! not subset $dlist{$_}++; } my @extra = (); #is subset, now see if any "extra's" foreach (keys %dlist) { push @extra, $_ if $dlist{$_} == 0; } return (1, @extra); } __END__ prints: listC contains all users and 1 additional addresses listA contains all users

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://864086]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (2)
As of 2021-07-26 13:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?