in reply to Multi-Dimensional Array to Hash Conversion Optimization

Huh? why not use
$ary_ref = $dbh->selectall_hashref($statement);
don't make things harder than they need to be! :)

Replies are listed 'Best First'.
Re^2: Multi-Dimensional Array to Hash Conversion Optimization
by tadman (Prior) on Apr 03, 2001 at 20:42 UTC
    Perhaps because of this:      Can't locate object method "selectall_hashref" via package "DBI::db" at test line 5. Update: It would seem that, as boo_radley pointed out below, there is an upgrade to DBI. Jumped the gun there, I guess, if only because I've assumed that such a thing existed before only to find run-time errors. (Heh, oops) Thanks for the explanation! That puts the stuff below into a pseudo-historical context then...

    I'm hoping that some day they will implement one. However, the idea was that I wanted to take an array containing (key,value) pairs inside their own ARRAY-ref and convert back.

    I had cooked up something like this before:
    sub selectall_hashref_byid { my ($table) = shift; my ($select); if (scalar(@_) == 1) { # Single key to fetch, so no HoH return { @{$db->selectall_arrayref("SELECT id,? FROM $ +_", $_[0])} }; } if (@_) { unshift (@_, 'id') unless (@_ && grep ("id", @_)); } else { @_ = ('*'); } my ($hash, $row, $query); $hash = {}; $query = $db->prepare ("SELECT ".join (',', @_)." FROM $table" +); $query->execute (); while (my $row = $query->fetchrow_hashref) { # Stoke it $hash->{$row->{id}} = $row; # Deredundantize it delete $hash->{$row->{id}}->{id}; } return $hash; }
    The only downside is that the crazy casting that goes on in there doesn't handle errors very well, so it is really flying by the seat of your pants.
      *smacks head*
      not everyone upgrades as rapidly as you do, boo...
      If you can, hie thee unto cpan:
      Changes in DBI 1.15, 28th March 2001 ... Added selectall_hashref thanks to Leon Brocard. ...
        You're quick on the upgrades, apparently. Nicely.

        The only downside is that selectall_hashref returns a ref to an array of hashes, not a hash of hashes based on a particular key field. Close, but not quite! Still, it has applications.

        Thanks for the tip!