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

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?

Replies are listed 'Best First'.
Re^5: Need to get the intersect of hashes
by moritz (Cardinal) on May 15, 2008 at 08:37 UTC
    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
Re^5: Need to get the intersect of hashes
by grizzley (Chaplain) on May 15, 2008 at 08:40 UTC
    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.
Re^5: Need to get the intersect of hashes
by ikegami (Patriarch) on May 15, 2008 at 15:11 UTC

    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"); } }