arrays - 如何从 Perl 中的数组中获取哈希值?

标签 arrays perl hash perl-data-structures

我想在 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/

相关文章:

c++ - 数组初始化在 C++ 中使用 const 变量

arrays - 如何从 C 指针创建 Racket 可变数组来修改 OpenCV 图像?

PHP:我可以在 array_map 函数中获取索引吗?

perl - 您如何处理多个 PostgreSQL 模式和 DBIx::Class?

perl - 如何检查是否导入了所有 Perl 模块?

r - 以双射方式将向量映射为整数

ruby - 在哈希中,如何为同一个键添加两个值而不是覆盖?

c# - 适用于字节数组的哈希码方法?

java - 将数组的String元素随机插入二维数组Java

regex - 将字符串截断至 PCRE 中的大小