Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

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

by rokadave (Sexton)
on Sep 20, 2005 at 16:27 UTC ( #493505=note: print w/ replies, xml ) Need Help??


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

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.


Comment on Re^2: Shortcut operator for $a->{'b'}=$b if $b;
Re^3: Shortcut operator for $a->{'b'}=$b if $b;
by ikegami (Pope) on Sep 20, 2005 at 16:32 UTC

    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

        overload doesn't define operators; it redefines them. ?= would have to be added to perl by patch.

        There is an alternative to a new or overloaded operator. One could use a tied hash. The only difference would be in the setter.

        By the way, my function does not autovivify. At least, not in 5.6.x or 5.8.x.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (8)
As of 2014-12-27 17:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (177 votes), past polls