关联数组 - PERL

Associative array - PERL

我需要知道在 Perl 中创建关联数组的方法。

基本上现在我有如下实现的代码:

 my $getEmployeeListOfTeamQuery  = "SELECT profiles.userid 
                                  FROM user_group_map,profiles 
                                  WHERE user_group_map.group_id = $teamId 
                                  AND profiles.userid = user_group_map.user_id 
                                  AND profiles.active = 'y' 
                                  AND profiles.login_name NOT LIKE 'qa_%' 
                                  AND profiles.disabledtext = '' 
                                  GROUP BY profiles.login_name 
                                  ORDER BY profiles.login_name";

    my $getEmployeeListOfTeam = $dbh->prepare($getEmployeeListOfTeamQuery);
    $getEmployeeListOfTeam -> execute();
    my @techs = ();

    while(my ($tech) - $getEmployeeListOfTeam->fetchrow_array) {
        push @techs,$tech;
    }

所以上面的代码将在 $getEmployeeListOfTeamQuery 中进行查询,将数组名称创建为 techs。

然后尝试将值推入数组。

这里运行良好。

我这里的问题是关于关联数组的创建。

也就是我需要查询如下:"SELECT profiles.userid, profiles,username....."

因此我需要创建一个关联数组,其中 "userid" 作为键,"username" 作为值。

我担心你用来学习 Perl 的资源。自 Perl 5 二十多年前发布以来,Perl 程序员就没有使用过术语 "associative array"。我们现在称这些结构为 "hashes"。如果您从使用术语 "associative array" 的资源中学习,那么它们几乎肯定已经过时了。

但是,回答你的问题。代码很简单。

my $sql = 'select profiles.userid, profiles.username...';
my $sth = $dbh->prepare($sql);
$sth->execute;

my %techs_hash;
while (my @row = $sth->fetchrow_array) {
  $techs_hash{$row[0]} = $row[1];
}

您可以通过一次调用 selectall_hashref:

将所有行提取到哈希的哈希中
 my $tech=$dbh->selectall_hashref("select profile.userid, profiles.username, ...",'userid');

或者您可以将所有行提取到具有 selectall_arrayref 和属性 {Slice=>{}} 的哈希数组中:

my $tech=$dbh->selectall_arrayref("select profile.userid, profiles.username, ...",{Slice=>{}});

然后把它变成你想要的散列(这正是你想要的):

my $result;
$result->{$_->{userid}}=$_->{username} foreach @$tech;

使用selectcol_arrayref()Columns属性:

my $aref = $dbh->selectcol_arrayref('select userid, login_name ...', {Columns => [1, 2]});
my %hash = @$aref;
my @l;
while(my $h = $sth->fetchrow_hashref){
  push @l,$h;
}
my %hash;
map { $hash{$_->{userid}} = $_->{username} } @l;