假设我有一个像这样的哈希
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:41:47
我要增加一个函数:
my %profile = (
building => scrub($p->{account}->{building}),
email => scrub($p->{account}->{email}),
phone => scrub($p->{account}->{phone}),
);并在函数中实现默认过滤逻辑。
或者,更好的是,将逻辑预先应用于$p,以便您知道$p有合理的值。
发布于 2011-03-17 14:52:37
因此,如果我正确地理解了您,您将有一堆虚假的东西被用作“使用默认值”的标志。我不确定您是要将所有这些转换为-1,还是要将特定值转换为字段。我将假设多个值,只是为了让事情变得更棘手。
# Make a hash of the wanted values
my %default_values = (
building => -1,
email => 'N/A',
phone => 'unlisted',
);
# Make a hash of the values to replace.
# Skip undef, we have to check that separately
my %bogus_values = map {$_ => undef} ('', '~', 0);
# Copy the goodies into your final structure
my %profile = map {
my $val = $p->{account}{$_};
$val = $default_values{$_}
if( not defined $val
or exists $bogus_values{$_}
);
$_ => $val;
} keys %default_values;
# Or copy them another way
my %profile = %default_values;
$profile{$_} = $p->{account}{$_}
for grep {
defined $p->{account}{$_}
and not exists $bogus_values{$_}
} keys %default_values;发布于 2011-03-17 14:33:09
从Perl5.10开始,您可以使用智能匹配
my @vals = (undef, '~', "");
$profile{building} = $p->{account}{building} ~~ @vals ? -1 : $p->{account}{building};https://stackoverflow.com/questions/5340363
复制相似问题