gpt4 book ai didi

perl - 在 Perl 中使用 map 仅在键存在时进行映射

转载 作者:行者123 更新时间:2023-12-03 20:52:38 25 4
gpt4 key购买 nike

我有一个这样定义的数据结构:

my @columns = (
{
db => 'location',
dt => 'location',
search => 'location',
},
{
db => 'name',
dt => 'name',
search => 'name',
},
{
db => 'iqs',
dt => 'iqs',
},
);

我正在像这样映射搜索的值:

@where = map +{ $_->{search} => { like => "\%$global_search\%" } }, @columns;

如果键搜索不存在,我最终会得到一个包含一堆这些的数据结构:

{
'' => {
'like' => '%pas%'
}
},

这完全搞砸了我想做的事情。所以,我想知道,既然 map 在技术上不是一个循环,那么当键搜索不存在时我该如何跳过?

编辑:

下面有人问过 map 和 loop 之间的性能差异,这激起了我的好奇心,所以我决定自己测试一下。以下是结果:

代码

#!/usr/bin/env perl
use strict;
use warnings;
use Benchmark qw/cmpthese timethese/;

my $global_search = 'test';


my @columns;
for ( my $i = 0; $i <= 100000; $i++ ) {
my $hash = {
db => "test$i",
dt => "test$i",
search => "test$i"
};
push @columns, $hash;
}

timethese(-30, {
mapBuild => sub {
my @where = map {
exists ($_->{search})
? +{ $_->{search} => { like => "\%$global_search\%" } }
: ()
} @columns;
},
forBuild => sub {
my @where;
foreach (@columns) {
if (exists $_->{search}) {
push @where, +{ $_->{search} => { like => "\%$global_search\%" } } ;
}
}
},
});

cmpthese(-30, {
mapBuild => sub {
my @where = map {
exists ($_->{search})
? +{ $_->{search} => { like => "\%$global_search\%" } }
: ()
} @columns;
},
forBuild => sub {
my @where;
foreach (@columns) {
if (exists $_->{search}) {
push @where, +{ $_->{search} => { like => "\%$global_search\%" } } ;
}
}
},
});

结果

Benchmark: running forBuild, mapBuild for at least 30 CPU seconds...
forBuild: 32 wallclock secs (31.66 usr + 0.00 sys = 31.66 CPU) @ 980.35/s (n=31038) mapBuild: 31 wallclock secs (31.58 usr + 0.00 sys = 31.58 CPU) @ 994.21/s (n=31397) Rate forBuild mapBuild forBuild 978/s -- -2% mapBuild 993/s 2% --

最佳答案

传递给 map 的 block 在列表上下文中被调用,因此它可以返回一个空列表:

@where = map {
exists ($_->{search})
? +{ $_->{search} => { like => "\%$global_search\%" } }
: ()
} @columns;

或者你可以先grep:

@where =
map +{ $_->{search} => { like => "\%$global_search\%" } },
grep exists($_->{search}),
@columns;

关于perl - 在 Perl 中使用 map 仅在键存在时进行映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26403412/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com