Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

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

by ikegami (Patriarch)
on Sep 20, 2005 at 16:24 UTC ( [id://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?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://493502]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (2)
As of 2024-04-24 14:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found