I find myself often writing code like this:
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 realize this is checking for true/false and not 'exists'. What I'm looking for is a concise functional equivalent to this.
Note you are checking $optionalParamsRef->{verbosity}
for true, not exist.
Possible way to do this:
foreach my $k (qw/verbosity param1 param2 param3/) { #Enumerate keys here
$settingsHash{$k} = $optionalParamsRef->{$k} if exists($optionalParamsRef->{$k});
}
As others mentioned, your code checks for false-ness. If you considered false values as non-existant, you could have used the logical or. Probably this is not what you want.
$settingsHash{verbosity} = $optionalParamsRef->{verbosity} || $default;
But maybe defined-ness is enough. It's still no check for existence, but if your hash doesn't contain undef
values, this could be enough:
$settingsHash{verbosity} = $optionalParamsRef->{verbosity} // $default;
using the "new" defined-or operator //
instead of the logical or ||
. I know these examples are not equivalent to the code you posted because they alwas assign something, but in my experience, this is often useful, so maybe it could help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With