Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

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 };


Comment on Re: Shortcut operator for $a->{'b'}=$b if $b;
Select or Download Code
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
Node Status?
node history
Node Type: note [id://493502]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (19)
As of 2015-07-02 19:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (45 votes), past polls