Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most concise way to assign value from hash only if it exists?

Tags:

perl

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.

like image 901
Adam S Avatar asked Feb 19 '23 09:02

Adam S


2 Answers

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});
}
like image 124
PSIAlt Avatar answered Feb 20 '23 21:02

PSIAlt


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.

like image 37
memowe Avatar answered Feb 20 '23 23:02

memowe