首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何设置默认值?

如何设置默认值?
EN

Stack Overflow用户
提问于 2011-03-17 14:24:46
回答 5查看 260关注 0票数 1

假设我有一个像这样的哈希

代码语言:javascript
复制
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 ~ ''

EN

Stack Overflow用户

发布于 2011-03-17 14:32:31

这类事情会处理虚值(比如undef''0'0'或其他我错过的东西):

代码语言:javascript
复制
my %profile = (
    building            => $p->{account}->{building} || -1,
    email               => $p->{account}->{email} || 'N/A',
    phone               => $p->{account}->{phone} || -1,
    );

您还可以使用定义的-或操作符//,只有在undef位于左侧时,才会使用默认值。

或照顾其他价值观:

代码语言:javascript
复制
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,
    );

(我可以建议改进设计,使其使用更一致的默认值吗?)

票数 0
EN
查看全部 5 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5340363

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档