假设我有一个像这样的哈希
my %profile = (
building => $p->{account}->{building},
email => $p->{account}->{email},
phone => $p->{account}->{phone},
);当未定义变量时,$p中的变量可以具有各种值。我至少见过undef ~ ''。
如果-1具有这些奇怪的默认值之一,如何将$profile{building}的值分配给例如$p->{account}->{building}?
有什么聪明的Perl方法可以做到这一点吗?
Update:任何值都可以接受任何奇怪的默认值undef ~ ''。
发布于 2011-03-17 14:32:31
这类事情会处理虚值(比如undef或''、0或'0'或其他我错过的东西):
my %profile = (
building => $p->{account}->{building} || -1,
email => $p->{account}->{email} || 'N/A',
phone => $p->{account}->{phone} || -1,
);您还可以使用定义的-或操作符//,只有在undef位于左侧时,才会使用默认值。
或照顾其他价值观:
my %bad_values_hash = map { $_ => 1 } ('~', ''); # Put your bad values in here
my %profile = (
building => ($bad_values_hash{$p->{account}->{building}} ? -1 : $p->{account}->{building}) // -1,
email => ($bad_values_hash{$p->{account}->{email}} ? 'N/A' : $p->{account}->{email}) // 'N/A',
phone => ($bad_values_hash{$p->{account}->{phone}} ? -1 : $p->{account}->{phone}) // -1,
);(我可以建议改进设计,使其使用更一致的默认值吗?)
https://stackoverflow.com/questions/5340363
复制相似问题