The most concise way to assign a value from a hash only if it exists?

I often find code of this type:

if ($optionalParamsRef->{verbosity}) { $settingsHash{verbosity} = $optionalParamsRef->{verbosity}; } 

However, it seems very verbose to repeat $optionalParamsRef->{verbosity} twice. Is there a shorter way?

Edit : Yes, I understand that this is / false authentication, not "exist". What I'm looking for is a brief functional equivalent of this.

+4
source share
4 answers

Note that you are checking $optionalParamsRef->{verbosity} for true , not .

Possible way:

 foreach my $k (qw/verbosity param1 param2 param3/) { #Enumerate keys here $settingsHash{$k} = $optionalParamsRef->{$k} if exists($optionalParamsRef->{$k}); } 
+4
source

As already mentioned, your code checks for falsity. If you considered false values โ€‹โ€‹non-existent, you could use boolean or. This is probably not what you want.

 $settingsHash{verbosity} = $optionalParamsRef->{verbosity} || $default; 

But perhaps a certain degree is enough. This still does not check for existence, but if your hash does not contain undef values, this may be enough:

 $settingsHash{verbosity} = $optionalParamsRef->{verbosity} // $default; 

using the "new" defined or operator // instead of boolean or || . I know that these examples are not equivalent to the code you posted because they assign something, but, in my experience, this is often useful, so maybe this can help.

+4
source
 my $v = $optionalParamsRef->{verbosity}; $settingsHash{verbosity} = $v if $v; 

 for ($optionalParamsRef->{verbosity}) { $settingsHash{verbosity} = $_ if $_; } 
0
source

Short functional equivalent:

 sub {$_[0]=$_[1] if $_[1]}->($settingsHash{verbosity}, $optionalParamsRef->{verbosity}); 

However, IMO, the main problem with your code is that you only conditionally set $ settingsHash {verbosity}, not allowing you to do something simpler:

 $settingsHash{verbosity} = $optionalParamsRef->{verbosity} || somedefault 

or even:

 %settingsHash = ( %defaultSettings, %$optionalParamsRef ); 
0
source

All Articles