in reply to how do i store the result from query into hash

While all the methods given are fine. . . there is a better, more efficient way. In stead of getting an array and assigning it to an hash, why not just get a hash? For example:

$hash_ref = $sth->fetchrow_hashref('NAME_lc');

NOTE: NAME_lc was passed so all names are converted to lower case(a _uc would cause upper case). This is because some databases change the case rather whimsically, for their own reasons. This way you can be sure that you are accessing the correct name.

(Programming The Perl DBI says, however, that in future releases, the DBI will implement the *same* hash return for memory efficiency; i.e., copying the data may be neccessary). UPDATE:I didn't fully answer the question, as arturo pointed out.

Replies are listed 'Best First'.
Re: Re: how do i store the result from query into hash
by arturo (Vicar) on Jun 19, 2001 at 01:03 UTC

    While the trick is nice for some purposes, note this doesn't yield up what the poster asked for. What you get out of your procedure, for each row, is a hash reference that looks like:

    #col1name and col2name are the names of the columns in the database $hash_ref = { col1name=>"orange", col2name=>"15" };

    But the poster wants to (essentially) turn a two-D array (which is what the result set is) into a hash, with the keys coming from column 1 and the values coming from column 2. While I'm here, thought I'd post something which is a little wacky, and probably less easily understood that Masem's answer (or my earlier one) but that illustrates what the poster wanted:

    # get whole result set into an array my @rs = @{ $sth->fetchall_arrayref() }; # each element of @rs is a reference to a two-member array #let's map the first elements to the keys of the hash # and the second elements to the values. my %hash = map { $_->[0] => $_->[1] } @rs;

    OK, I'll cop to listening to Van Halen on the internet radio, so I had to execute a little guitar-solo.

    perl -e 'print "How sweet does a rose smell? "; chomp ($n = <STDIN>); +$rose = "smells sweet to degree $n"; *other_name = *rose; print "$oth +er_name\n"'