Pergunta

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

Foi útil?

Solução

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

Outras dicas

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

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

delete @h{ grep { $h{$_} =~ /hello/ } keys %h };
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top