D
David Filmer
(I'm gonna use a DBI query as an example, but this question is really
a Perl syntax inquiry (how to add elegance to a bit of code), not a
database question).
Suppose I have a database table "department" with a simple structure
such as:
id integer primary key #might not be sequential because of
deletes
name varchar
I want to build a hash (%dept) from the database such that (for
example) $dept{2} eq "Accounting".
I access the database:
$sth = $dbh->prepare("SELECT id, name FROM department");
$sth->execute;
Now, I COULD do this:
$dept_ref = %{$sth->fetchall_hashref('id')};
Which gives me a situation where $dept_ref->{2}->{'name'} eq
"Accounting" - not really very close to the data structure I want (a
simple hash). So I COULD, instead, populate a hash like this:
%dept = %{$sth->fetchall_hashref('id')};
That gets me closer - now $dept{2}{'name'} eq "Accounting." DBI does
this, of course, because I might be selecting multiple columns. But,
in this case, I'm only selecting a key/value pair from the database
and would like to go directly to a simple hash. But I need an EXTRA
STEP to get to my goal - something like this:
$dept{$_} = $dept{$_}{'name'} for keys %dept; #now $dept{2} eq
'Accounting'
That got me what I wanted, but it's not elegant - I had to populate
the hash and then manipulate it. Is there an elegant way I can express
the subroutine call (in this case to fetchall_hashref) so that it does
this in just one step?
a Perl syntax inquiry (how to add elegance to a bit of code), not a
database question).
Suppose I have a database table "department" with a simple structure
such as:
id integer primary key #might not be sequential because of
deletes
name varchar
I want to build a hash (%dept) from the database such that (for
example) $dept{2} eq "Accounting".
I access the database:
$sth = $dbh->prepare("SELECT id, name FROM department");
$sth->execute;
Now, I COULD do this:
$dept_ref = %{$sth->fetchall_hashref('id')};
Which gives me a situation where $dept_ref->{2}->{'name'} eq
"Accounting" - not really very close to the data structure I want (a
simple hash). So I COULD, instead, populate a hash like this:
%dept = %{$sth->fetchall_hashref('id')};
That gets me closer - now $dept{2}{'name'} eq "Accounting." DBI does
this, of course, because I might be selecting multiple columns. But,
in this case, I'm only selecting a key/value pair from the database
and would like to go directly to a simple hash. But I need an EXTRA
STEP to get to my goal - something like this:
$dept{$_} = $dept{$_}{'name'} for keys %dept; #now $dept{2} eq
'Accounting'
That got me what I wanted, but it's not elegant - I had to populate
the hash and then manipulate it. Is there an elegant way I can express
the subroutine call (in this case to fetchall_hashref) so that it does
this in just one step?