in reply to Re^2: Need to get the intersect of hashes
in thread Need to get the intersect of hashes

You don't need to search in hash. If you have a key, you just retrieve the value connected with key. Can you print both structures, which you have, with help of Data::Dumper and append to your question?
  • Comment on Re^3: Need to get the intersect of hashes

Replies are listed 'Best First'.
Re^4: Need to get the intersect of hashes
by jbush82 (Novice) on May 15, 2008 at 08:28 UTC
    I've appended the output of one of my hashes (the other is similar, but MUCH longer.. thousands of files). I'm trying to use the following code:
    foreach my $intersect_file(@intersect_keys) { my $exec = $system_file_data{$intersect_file}; print $exec; }
    ... but $exec outputs as ARRAY(0x1a1c4ec)ARRAY(0x2bb0d9c) instead of the values of each key. Could the problem be that I have more than one value in some of the keys?
      Could the problem be that I have more than one value in some of the keys?

      Yes.

      foreach my $intersect_file(@intersect_keys) { my $exec = $system_file_data{$intersect_file}; my @values = ref $exec ? @$exec : ($exec); print "$_\n" for @values; }

      See perlreftut and perldsc for more information about nested structures.

        It seems to me that it makes more sense to have every hash element contain a reference to an array instead of having an array reference in some elements and values in others. That makes your code a _lot_ easier. No checking every time you access it, no do this in some cases/do that in other cases.

        --
        Wade
      Bingo! I thought so :) It is not a hash - it is hash of arrays and that's the place where you have to get familiar with references. $system_file_data{$intersect_file} gives you in return reference to an array, so you must do:
      $array_ref = $system_file_data{$intersect_file}; @array = @$array_ref; print @array; # or print $array[0];
      Check the other hash, it should be accessible in similar way, too.
        Awesome, now I get it.. I've been trying to figure out how to treat a key with multiple values it as an array.

        Thanks for the help guys.

      Could the problem be that I have more than one value in some of the keys?

      No, because it's impossible for a hash to have more (or less) than one value per key. Your values are references to arrays. The referenced arrays may containing any number of values, but the values of your hash are simply references.

      Once you fetch the reference, you may iterate over the referenced array:

      foreach my $intersect_file (@intersect_keys) { my $execs = $system_file_data{$intersect_file}; # Array ref foreach my $exec (@$exec) { print("$exec\n"); } }

      It could also be written as the following, but I prefer the former:

      foreach my $intersect_file (@intersect_keys) { foreach my $exec (@{ $system_file_data{$intersect_file} }) { print("$exec\n"); } }