jp922898
jp922898

Reputation: 69

Delete keys from hash map in perl which matches values from array

I would like to use Perl to delete keys from a hash map that match values in a given array.

Example:

Input:

   @array = ("apple", "banana" , "cherry")
   %hash = ( '/abc/apple/somestring' => val1,
             '/banana/somestring/somesting' => val2,
             '/xyz/apple/somestring'   => val3,
             '/somestring/somestring/'        => val4,
             '/xyz/somestring/random'        => val2,
           )

Output:

   %hash = ( '/somestring/somestring/'        => val4,
             '/xyz/somesting/random'        => val2,
           )

Upvotes: 1

Views: 3008

Answers (1)

amon
amon

Reputation: 57646

Simple:

  1. For each element in the array, select the matching hash keys

    for my $elem (@array) {
      my @matching_keys = grep { 0 <= index $_, $elem } keys %hash;
    
  2. Then, delete the hash entries with the matching keys:

      delete @hash{@matching_keys};
    }
    

The 0 <= index $_, $elem could also be written as /\Q$elem/, if you are optimising for readability instead of speed.


Alternatively: build a regex that matches all elems in the array:

my $rx = join '|', map quotemeta, @array;

Then, select and delete all keys that match this regex:

my @matching_keys = grep /$rx/, keys %hash;
delete @hash{@matching_keys};

This should be more efficient.

Upvotes: 4

Related Questions