in reply to Re^3: Elegance, dammit!
in thread Elegance, dammit!

(Sorry for the long delay; I got bushwhacked by Real Life, but managed to survive it.)

I'd tried using selectall_hashref originally - that is, in fact, the first approach I tried - but I recall being unsatisfied with the output. I just went back and reproduced what I'd done then, and the problem turns out to be that either the docs don't tell you how to do what I need to do, or it just can't be done with selectall_hashref. In short, here are the problems:

1) Remapping that hashref into the arrayref that I want isn't any easier than what I was looking for - unless I've missed something.

2) The output format is... graceless. Perhaps it is, as you say, that I'm missing something - but I want two columns as an arrayref keyed by date, and what selectall_hashref returns is

'2007-05-13' => { subject => 'foobar', date => '2007-05-13', # Erm... label => 'xyz' }

The statement that I'm using is one I showed previously:

my $ref = $dbh->selectcol_arrayref( "select date, label, subject from travel where date >= curdate()-5 + order by date", { Columns=>[1,2,3] } );

If you can show me how to do this better with selectall_hashref, I'd be grateful.

Replies are listed 'Best First'.
Re^5: Elegance, dammit!
by ysth (Canon) on Jun 19, 2007 at 18:07 UTC
    Now I'm not sure what format you are actually looking for. I originally thought you wanted a hash of arrayrefs, where the arrays contain the label and subject fields and the hash is keyed by date. But I'm not sure what "two columns as an arrayref keyed by date" looks like. Assuming the former is correct, you'd do it like this:
    my $ref = $dbh->selectall_hashref(... for my $row (values %$ref) { $row = [ @$row{qw/label subject/} ]; } # or # $_ = [ @$_{qw/label subject/} ] for values %$ref; # or # $ref = { map {; $_, [ @{$ref->{$_}}{qw/label subject/} ] } keys %$re +f };
    But it would make more sense to me to just leave it as a hash of hashes; unless there are extreme efficiency issues to concern you, I prefer hashes over arrays when the values are different types of things (in this case, label and subject).