the_mind_ has asked for the wisdom of the Perl Monks concerning the following question:

I have a file with some id number (one on each line).
I have loaded the file into an array.
And i also have a hash with some other id numbers.

And now to the question: (does it show that i haven't user perl for some time?)

How can i compare the array with the hash?
I need to know:
If the hash contains one of the values in the array.
If the hash contains a value that don't exists in the array.
If the array contains a value that don't exists in the hash.

Some solid code would be apriciated. Or a link to a example.

Replies are listed 'Best First'.
Re: Compare array - hash
by MungeMeister (Scribe) on Jan 15, 2002 at 00:30 UTC
    Here's a method I use. It may not be the most efficient or elegant, but it works.

    Basically, I use a hash array to get a union of the array and the hash (it could just as easily be 2 hashes), while keeping track of where the data came from....

    Note that I stuck in some dummy data....

    use strict; my @user = (1,3,5,7,9); my %log = ( 1 => 'today', 2 => 'today', 3 => 'yesterday', 4 => 'last week', 5 => 'now' ); my %result; foreach my $x (@user) { # Save the id ($x) in the result hash, save the location # of data as value, 'both' if $log{$x} exists, user if not $result{$x} = $log{$x} ? 'both' : 'user'; } foreach my $y (keys %log) { # Save the id ($y) in the result hash, save the location # of data as value only if the id does not exist in result # hash yet $result{$y} = 'log' unless $result{$y}; } foreach my $z (sort keys %result) { print "$z: $result{$z}\n"; }
    Here are the results:

    1: both 2: log 3: both 4: log 5: both 7: user 9: user


    Hope this helps.

    Brian
Re: Compare array - hash (boo)
by boo_radley (Parson) on Jan 14, 2002 at 21:48 UTC
      first you'd get the values of the hash.

      Inversely, it might be more effective to put the array into a hash.
      @file_contents_array = <FH>; %file_contents = map {$_ => 1} @file_contents_array; # Now you can more easily compare # %file_contents with your existing hash