Question

I have a hash in Perl which stores a simple key value look up as shown below

'a' => hello
'b' => world
'c' => hellooo

I would like to efficiently delete all key value pairs that have the pattern "hello" in them. Is this easily possible through grep Thanks in advance

Was it helpful?

Solution

You can use a hash slice here. Hash slices return the values associated with a list of keys.

To remove key/value pairs at once, you could do something like this..

my $regex = qr/hello/;
delete @h{ grep { $h{$_} =~ $regex } keys %h };

OTHER TIPS

for (keys %h) {
   delete $h{$_} if $h{$_} =~ /hello/;
}

delete $h{$_} for grep { $h{$_} =~ /hello/ } keys %h;

delete @h{ grep { $h{$_} =~ /hello/ } keys %h };
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top