in reply to
Shortcut operator for $a->{'b'}=$b if $b;
No-one's mentioned using tie.
package Tie::Hash::OnlyIf;
sub STORE {
my $self = shift;
my ($key, $val) = @_;
if ( $val ) {
$self->{$key} = $val;
}
}
package main;
tie my %data, Tie::Hash::OnlyIf;
$data{b} = $b;
The only problem with this is that the casual reader will expect that the key 'b' will exist. But, it is a solution.
Oh - and tie's a lot slower than normal hashes, but performance is almost always overvalued. Going from 0.01 to 0.08 seconds per execution isn't noticeable.
My criteria for good software:
- Does it work?
- Can someone else come in, make a change, and be reasonably certain no bugs were introduced?