Search code examples
perlgrepdereference

Doubts about grep and dereference


Do you have an idea of what is this code doing?

my(%p,%q);
grep {$p{$_}++} @{$_[0]};
grep {$q{$_}++} @{$_[1]};
[grep {$p{$_} and !$q{$_}} keys %p];

I'm kind of translating this code to .Net, but I'm not completely sure of what this is doing, this subroutine ask for 2 parameters, in the case I working on, 2 hashtables.

Let me know if you need more information


Solution

  • This is the body of a function that accepts two array references as parameters. Then it returns an array reference that contains the unique values in the first array that are not in the second array.

    Given that the new array is iterating on the keys of %p, it's actually unnecessary to include the $p{$_} test in the grep.

    Overall, I'd probably rewrite the sub as follows:

    my ($array1, $array2) = @_;
    
    my %in_array2 = map {$_ => 1} @$array2;
    
    my %seen;
    
    return [grep {!$in_array2{$_} && !$seen{$_}++} @$array1]