2

I have the following hash: %{$data{$id}{$date}} that includes a large number of dates

and an array @dates that includes a subsection of dates found in the %hash.

What is the best way to loop through my %hash and delete all dates that are not found in @dates array? Once this is done I'd like the %hash to only have the values from @array dates.

I've tried 'delete unless exists' looking at keys after I created a hash from my @dates array but would get missing arguments error.

1
  • 3
    Please edit and show us the actual code you wrote that includes delete unless exists and the exact error message. Commented Jun 27, 2018 at 16:54

2 Answers 2

4

You should loop through the keys of %{$data{$id}} instead.

my %dates = map {$_ => 1} @dates;
exists $dates{$_} or delete $data{$id}{$_} for keys %{$data{$id}};
Sign up to request clarification or add additional context in comments.

Comments

3

As long as the dates in @dates are guaranteed to appear in the hash you can use map

%{ $data{$id} } = map { $_ => $data{$id}{$_} } @dates

5 Comments

Good alternative. $data is a reference to a hash so you need to write $$data{$id}{$_} instead of $data{$id}{$_}.
@blhsing: If $data is a hash reference then the OP's code is wrong, and I have no reason to assume so.
@blhsing: Even if you were correct, it would be best to write $data->{$id}{$_}
@borodin Thanks! This filtered out all the correct dates but I end up with undef hash for all but the last date. I'll work on debugging this.
You don't describe your data structure very carefull and I may have misunderstood it. If you add a dump of your hash into the question then it will help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.