0
votes

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

1
use Data::Dumper; print Dumper(\%ARGS); to see the structure of %ARGS. Then you can show us an example in the same format.RobEarl
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 ...))TLP
No I should modify the same hash with the minimum set of keys and nothing else .user2890683
You mean you should delete all keys from %ARGV except the minimum set, key1, key2, ...?TLP
yes that's exactly what I need to douser2890683

1 Answers

0
votes

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