Domanda

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

È stato utile?

Soluzione

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

Altri suggerimenti

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

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

delete @h{ grep { $h{$_} =~ /hello/ } keys %h };
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top