0

I have a perl hash passed to me in %ARGS. I have to implement the functionality wherein if for a required minimum set of keys(say key1,key2,key3,key4,key5) there are multiple values in the hash then I need to get the first value and populate the hash with the minimum set of keys.

Currently I have.

while (my ($key, $value) = each(%ARGS)) {
    #check if key is equal to the keys from the set.
    if (ref($value) ) {
          #means its a nested key value pair.
          extract first value and put it for the key 

How do I establish that. Any pointers would be useful

5
  • 1
    use Data::Dumper; print Dumper(\%ARGS); to see the structure of %ARGS. Then you can show us an example in the same format. Commented May 28, 2014 at 10:44
  • Is your task to copy the selected key/value pairs to another hash? If so, why not just loop over the selected keys? for (qw(key1 key2 ...)) Commented May 28, 2014 at 10:54
  • No I should modify the same hash with the minimum set of keys and nothing else . Commented May 28, 2014 at 11:03
  • You mean you should delete all keys from %ARGV except the minimum set, key1, key2, ...? Commented May 28, 2014 at 11:08
  • yes that's exactly what I need to do Commented May 28, 2014 at 11:35

1 Answer 1

0

It sounds like you just need to create a hash of default values.

You can use that hash to initialize your primary hash to ensure each of the keys exists. And then you can use the same hash to restrict the %ARGS hash to only those keys you want it to have:

my %def_args = (
    key1 => '',
    key2 => '',
    key3 => '',
    key4 => '',
    key5 => '',
);

# Selectively Initialize Args with Defaults:
%ARGS = (%def_args, %ARGS);

# Restrict ARGS to just default keys
delete @ARGS{grep {! exists $def_args{$_}} keys %ARGS};
Sign up to request clarification or add additional context in comments.

2 Comments

What about the case where if multiple values exists for the key then I need to choose the first one.
Hash keys are unique. If you think there are multiple values, then you aren't explaining your situation accurately. Feel free to edit your original question to more fully describe your situation and the problem your facing.

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.