http://www.perlmonks.org?node_id=493502


in reply to Shortcut operator for $a->{'b'}=$b if $b;

I assume you mean $b is a long expression, so you'd rather avoid having it twice. If so, you could topicalize $b:

{ local $_ = $b; $a->{b} = $_ if defined $_; }

or (update)

$a->{b} = $_ foreach grep defined, $b;

or you could add everything then remove undefined values:

delete @$a{ grep { not defined $a->{$_} } keys %$a };

Replies are listed 'Best First'.
Re^2: Shortcut operator for $a->{'b'}=$b if $b;
by rokadave (Sexton) on Sep 20, 2005 at 16:27 UTC
    Yes. If there's no shortcut operator, then your suggestion is the cleanest it'll get. I was hoping there existed an "assign-if-true" operator.

      You could write the operator yourself:

      sub assign_if_defined { $_[0] = $_[1] if defined $_[1]; } assign_if_defined($a->{'b'}, $b);

      By the way, I'm using defined since you said you didn't want empty keys. Checking for truthfullness (as you have been doing) removes both empty and false keys. Just remove the word defined for a truth test.

        Maybe someone can suggest how to define a '?=' operator

        $a->{'b'} ?= $b;

        assigns $b to $a->{'b'} if $b is defined, does not autovivify $a->{'b'} if $b not defined

        is that possible? - I'm thinking of use overload but I dimly recall that there is a finite set of operators you can overload and ?= isnt one of them.

        ...reality must take precedence over public relations, for nature cannot be fooled. - R P Feynmann