rokadave has asked for the
wisdom of the Perl Monks concerning the following question:

I'm making a data structure and I don't want any empty keys.
This code works:
$a->{'b'}=$b if $b;
The problem is that's way too verbose... and the real code is much uglier than that.
I was wondering if there's some great shortcut operator. I got excited about ||=, but it's not really the samething. ? and : don't exactly work either. The point is to have no key 'b' exist if $b is false.

Comment on
Shortcut operator for $a->{'b'}=$b if $b;
Replies are listed 'Best First'.

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.

It's slightly OT, but you probably want to avoid using $a and $b (even as metasyntax), as they are used in sort code blocks. As such, they are exempted from strict checking, and could introduce subtle bugs.

Note: that should probably be unless defined $a->{$_} so we don't remove false keys, but I made the choice to mirror the OP's syntax.

<-radiant.matrix->Larry Wall is Yoda: there is no try{} (ok, except in Perl6; way to ruin a joke, Larry! ;P)
The Code that can be seen is not the true Code"In any sufficiently large group of people, most are idiots" - Kaa's Law

I guess I don't really understand where your "way too verbose" is coming from; it would help if I could see a more involved example of the code you're attempting to simplify.

<-radiant.matrix->Larry Wall is Yoda: there is no try{} (ok, except in Perl6; way to ruin a joke, Larry! ;P)
The Code that can be seen is not the true Code"In any sufficiently large group of people, most are idiots" - Kaa's Law