我想在 perl 中编写一个小“DBQuery”函数,这样我就可以有一个单行程序,它发送一个 SQL 语句并接收回一个散列数组,即一个记录集。但是,我遇到了 Perl 语法问题(可能还有一些奇怪的指针/引用问题),这使我无法从数据库中获取的散列中打包信息。下面的示例代码演示了该问题。
我可以使用以下语法从数组内的散列中获取数据“Jim”:
print $records[$index]{'firstName'}
返回“吉姆”
但是如果我首先将数组中的哈希记录复制到它自己的哈希变量中,那么奇怪的是我无法再访问该哈希中的数据:
%row = $records[$index];
$row{'firstName'};
返回“”(空白)
这是显示问题的完整示例代码。任何帮助表示赞赏:
my @records = (
{'id' => 1, 'firstName' => 'Jim'},
{'id' => 2, 'firstName' => 'Joe'}
);
my @records2 = ();
$numberOfRecords = scalar(@records);
print "number of records: " . $numberOfRecords . "\n";
for(my $index=0; $index < $numberOfRecords; $index++) {
#works
print 'you can print the records like this: ' . $records[$index]{'firstName'} . "\n";
#does NOT work
%row = $records[$index];
print 'but not like this: ' . $row{'firstName'} . "\n";
}
最佳答案
嵌套数据结构包含散列引用,而不是散列。
# Will work (the -> dereferences the reference)
$row = $records[$index];
print "This will work: ", $row->{firstName}, "\n";
# This will also work, by promoting the hash reference into a hash
%row = %{ $records[$index] };
print "This will work: ", $row{firstName}, "\n";
如果您曾经接触过深入的 Perl 数据结构,您可能会从使用 Data::Dumper 打印它中获益。将其打印为人类可读(和 Perl 可解析)的形式。
关于arrays - 如何从 Perl 中的数组中获取哈希值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51195/