The "fetch*" methods family mostly about returning a row, one at a time. The "*array_ref" indicates that a row will be returned as an array reference, so virtually you get ['value', 'for', 'each', 'column'] instead of ('value', 'for', 'each', 'column'). The "all" part indicates that all that array references will be returned, representing all results match the query. And the whole is bundled in another array reference. So you end up with AoA:
$all_rows = [
[R1C1, R1C2, ..., R1Cn],
[R2C1, R2C2, ..., R2Cn],
...,
[RnC1, RnC2, ..., RnCn],
];
Doesn't DWIW! If I do this:
...
that is, I've got an AoA -- I just want ... an A!
Well, AFAIK, Perl is more DWIM rather than DWIW. You may W an A, but by using fetchall_arrayref, you really M AoA. If you really M an A and you only want a single column from each row, then you can use selectcol_arrayref instead.
# Table: group
# Columns: id, name
# Values: 1, Admin
# 2, User
# 3, Public
my $sql = 'select * from group';
my $r = $dbh->selectcol_arrayref($sql); # default to first column
# or, if you want the the 'name' column
my @r = @{$dbh->selectcol_arrayref($sql, {Columns=>[2]})}; # we want t
+he 2nd column
# if you know the column name you want in advanced:
my $sql2 = 'select name from group';
my @group_names = @{$dbh->selectcol_arrayref($sql2)};
print Data::Dumper->Dump(
[$r, \@r, \@group_names],
[qw(id name group_names)],
);
Output with Data::Dumper:
$id = [
'1',
'2',
'3',
];
$name = [
'Admin',
'User',
'Public',
];
$group_names = [
'Admin',
'User',
'Public',
];
Update: (09-07-2007) Fixed typo, corrected syntax to Data::Dumper->Dump() (was Data::Dumper(...)). I know I should just copy/paste instead of retyping. *sighs*
Open source softwares? Share and enjoy. Make profit from them if you can. Yet, share and enjoy!
| [reply] [d/l] [select] |
| [reply] |
fetchall_arrayref fetches rows and each row may contain many fields, hence the AoA structure.
DWIM is Perl's answer to Gödel
| [reply] [d/l] |
my @data = map { $_->[0] } @{ $sth->fetchall_arrayref };
| [reply] [d/l] |
use DBIx::Simple;
my @names = $db->query('SELECT name FROM people WHERE id > 5')->flat;
fetches everything into "one big flattened list." | [reply] [d/l] |