Frage

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

War es hilfreich?

Lösung

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

Andere Tipps

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

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

delete @h{ grep { $h{$_} =~ /hello/ } keys %h };
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top