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

  Main Index MAIN
Search Posts SEARCH
Who's Online WHO'S
Log in LOG

Home: Perl Programming Help: Intermediate:
ARRAYs vs. HASHs w/ DBs..which is better



Sep 21, 2001, 10:38 PM

Post #1 of 2 (1089 views)
ARRAYs vs. HASHs w/ DBs..which is better Can't Post

Currently, I dump all my data into arrays and process the arrays in for loops. This has been working great for me but as I read more and more Perl books, the use of HASH seems to predominate the use of arrays.

Which is more attuned to the task of dealing with database data?

(this may seem a strange question) If a hash is better, how is it used in comparison to an array (since all the books I read don't list comparisions of the two types).


Sean Shrum

User / Moderator

Sep 23, 2001, 5:57 PM

Post #2 of 2 (1077 views)
Re: ARRAYs vs. HASHs w/ DBs..which is better [In reply to] Can't Post

When you use you get a set of functions...

  @row_ary  = $sth->fetchrow_array; 
$ary_ref = $sth->fetchrow_arrayref;
$hash_ref = $sth->fetchrow_hashref;

Which will grab the next row after you use these two lines...

	my $sth = $dbh->prepare ($query); 
$sth->execute ();

If you ask to fetch a row as an array you will get back N things. If you ask for it as a hash you get 2N things, as each thing gets a key and a value rather than just a value. If you are only grabing one or two items on each row, you are really concerned with speed, or you are not doing much processing (such as just dumping it to an html table) then the array solution is the way to go. But if you are trying to remember what a particular item in the array is, or you are doing interesting stuff to the results from each row, it may be easier to work with as a hash.

But it is a tradeoff of speed for understanding.

In this case you would use them as...

while (my @row_ary = $sth->fetchrow_array ()) { 
print $row_ary[0];

while (my $ary_ref = $sth->fetchrow_arrayref()) { 
print $ary_ref->[0];

while (my $hash_ref = $sth->fetchrow_hashref ()) { 
print $hash_ref->{key1};


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

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