DBI::fetchall_arrayref 的 Perl 数组取消引用问题
我是 Perl 新手,在取消引用 DBI 模块中 fetchall_arrayref 所导致的数组时遇到问题:
my $sql = "SELECT DISTINCT home_room FROM $classlist";
my $sth = $dbh->prepare($sql);
$sth->execute;
my $teachers = $sth->fetchall_arrayref;
foreach my $teacher (@{$teachers}) {
print $teacher;
}
运行此命令将打印引用而不是数组中的值。
但是,当我运行时:
my $arrref = [1,2,4,5];
foreach (@{$arrref}) {
print "$_\n";
}
我得到了数组的值。
我做错了什么?感谢您的帮助!
杰夫
I'm a Perl newbie and am having issues with dereferencing an array that is a result of fetchall_arrayref in the DBI module:
my $sql = "SELECT DISTINCT home_room FROM $classlist";
my $sth = $dbh->prepare($sql);
$sth->execute;
my $teachers = $sth->fetchall_arrayref;
foreach my $teacher (@{$teachers}) {
print $teacher;
}
Running this will print the reference instead of the values in the array.
However, when I run:
my $arrref = [1,2,4,5];
foreach (@{$arrref}) {
print "$_\n";
}
I get the values of the array.
What am I doing wrong? Thank you for your help!
Jeff
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
来自文档
因此,在您的示例中,
$teacher
是一个 ARRAY 引用。所以你需要循环遍历这个数组引用
From the doc
So in your example,
$teacher
is an ARRAY ref.So you will need to loop through this array ref
如果您只想提取教师列,则需要使用:
if you want to extract only the teacher column, you want to use:
fetchall_arrayref
获取查询的所有结果,因此您实际返回的是对数组数组的引用。返回的每一行将是列的 arrayref。由于您的查询只有一列,您可以说:得到您想要的。
查看更多内容:
Perl 中的数组的数组。
fetchall_arrayref
fetches all the results of the query, so what you're actually getting back is a reference to an array of arrays. Each row returned will be an arrayref of the columns. Since your query has only one column, you can say:to get what you want.
See more:
Arrays of arrays in Perl.
您有对行数组的引用。每行都是对字段数组的引用。
您会看到 Data::Dumper 的差异。
You have a reference to an array of rows. Each row is a reference to an array of fields.
You would have seen the difference with Data::Dumper.
$sth->fetchall_arrayref
返回对每行包含一个引用的数组的引用!请在此处查看 DBI 文档。
$sth->fetchall_arrayref
returns a reference to an array that contains one reference per row!Take a look at DBI docs here.
根据 DBI 的 fetchall_arrayref() 的文档:
您只需要一层间接:
数据结构有时可能有点难以可视化。当发生这种情况时,我求助于
Data::Dumper
,以便我可以插入这样的行:我发现有时通过转储数据结构,我会得到一个即时地图,在创建时用作参考点操作该结构的代码。我最近经历了一场真正的结构噩梦,只是偶尔使用 Dumper 来理顺我的头。
Per the documentation of DBI's fetchall_arrayref():
You're one level of indirection away:
The data structure might be a little hard to visualize sometimes. When that happens I resort to
Data::Dumper
so that I can insert lines like this:I've found that sometimes by dumping the datastructure I get an instant map to use as a reference-point when creating code to manipulate the structure. I recently worked through a real nightmare of a structure just by using Dumper once in awhile to straighten my head out.
您可以使用 map 取消引用返回的结构:
现在您有一个简单的教师数组。
You can use map to dereference the returned structure:
Now you have a simple array of teachers.