in reply to (boo) Re: Multi-Dimensional Array to Hash Conversion Optimization
in thread Multi-Dimensional Array to Hash Conversion Optimization

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.

Replies are listed 'Best First'.
(boo) Re:x3 Multi-Dimensional Array to Hash Conversion Optimization
by boo_radley (Parson) on Apr 03, 2001 at 20:47 UTC
    *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!
        really? I wish I had time to play with it right now...
        If I understand you correctly, you can the same functionality, that is, an array of hashes, from
        my $result_ref = $l_sth->fetchall_arrayref({})
        You can then do things like $$result_ref[0]{field} the above two lines are from code running on production machine; I know it works because my pager is too quiet for it to be otherwise.
        But for 1.15's fetchall_hashref, I haven't looked yet. Must play later.