Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

Re: Shortcut operator for $a->{'b'}=$b if $b;

by ikegami (Pope)
on Sep 20, 2005 at 16:24 UTC ( #493502=note: print w/replies, xml ) Need Help??

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

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://493502]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (5)
As of 2018-02-24 09:14 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (310 votes). Check out past polls.