arraysperlassociative-array

Associative array in Perl


I need to know the way of creating the associative array in Perl.

Basically, now I have the code which is implemented as follows:

 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;
    }

So the above code will be having the query in $getEmployeeListOfTeamQuery. It created the array names as techs.

Then I tried pushing the values into the array.

Here it is working fine.

My question here is regarding the creation of the associative array.

That is, I need to query as follows: "SELECT profiles.userid, profiles,username....."

Hence I need to create an associative array with "userid" as the key and "username" as the value.


Solution

  • I worry about the resources that you are using to learn Perl. Perl programmers haven't used the term "associative array" since Perl 5 was released over twenty years ago. We now call these structures "hashes". If you're learning from resources that use the term "associative array", then they are almost certainly horribly outdated.

    But, to answer your question. The code is pretty simple.

    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];
    }