CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Store muliple values to a key for a hash that will be used by two tables....

 



starburst
New User

Apr 13, 2010, 12:25 PM

Post #1 of 2 (787 views)
Store muliple values to a key for a hash that will be used by two tables.... Can't Post

I have two database tables, one with two columns (a user and an id) and another with several columns. The only data these two different database tables have in common is the 'id' column... I am stumped at how to store the values for the id from the first table to a unique user variable (because one user could have multiple ids).

here is what I have started:

Code
     #Search the database if search was pressed 
if ( defined $form{cmd} && $form{cmd} eq "Search" ) {
$sqlcmd = "SELECT * from `$Database`.`$AccessTable` WHERE ";
$pattern = SafeStr($form{SearchQuery});
}

foreach $member (@tblentries) {
$mname = $member->{"member"}; #name (this case either id or user)
$mtype = $member->{"type"}; #variable type (either string or int)
$val = $member->{"val"); #actual value

....


If I could create some hash like %user, and then like this:

Code
 push @{$user{$pattern}, $ID}


push an ID value into an array of IDs for a specific user it would be ideal...I just don't know how to start it.

PLEASE help me :)


7stud
Enthusiast

Apr 13, 2010, 12:46 PM

Post #2 of 2 (785 views)
Re: [starburst] Store muliple values to a key for a hash that will be used by two tables.... [In reply to] Can't Post

The idiom is: "look up the value for a key, and push an element onto the array if it exists, otherwise create an empty array and push an element onto the empty array".


Code
use strict; 
use warnings;
use 5.010;

my %ids_for = (
Tom => [10, 20],
Jane => [100, 200],
);

my @names = qw{
Tom
Dick
Jane
};

my $new_id = 1_000;

for my $name (@names) {
push @{ $ids_for{$name} }, $new_id;
}

while ( my($name, $aref) = each %ids_for ) {
say "$name --> @$aref";
}

--output:--
Jane --> 100 200 1000
Dick --> 1000
Tom --> 10 20 1000


When you do this:


Code
push @{ $ids_for{$name} }, $new_id


...perl does some magic. If there is no value for the key, perl notices that you are dereferencing the non-value with @, so perl creates an empty array for you, adds the element to the array, and assigns the array to the key.


(This post was edited by 7stud on Apr 13, 2010, 12:50 PM)

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives