在循环遍历DB数据集时,在不使用数组的情况下将唯一哈希数据放入JSON对象的最佳方法是什么?

在循环遍历DB数据集时,在不使用数组的情况下将唯一哈希数据放入JSON对象的最佳方法是什么?,json,perl,hash,Json,Perl,Hash,我需要将数据放入JSON对象中,但因为我使用的是%data散列,并且它具有相同的地址,所以我在JSON对象中重复获取相同的数据 这是生成JSON的代码 while (my ($orderID, $possessorName, $itemDescription, $...) = $sth->fetchrow_array) { %data = (orderID => $orderID, possessorName =>

我需要将数据放入JSON对象中,但因为我使用的是
%data
散列,并且它具有相同的地址,所以我在JSON对象中重复获取相同的数据

这是生成JSON的代码

            while (my ($orderID, $possessorName, $itemDescription, $...) = $sth->fetchrow_array) 
        {
            %data = (orderID => $orderID, possessorName => $possessorName, itemDescription => $itemDescription,...);


            $query_results{"job$index"} = {"data" => \%data};

            $index++;

        }




        return $json_obj->pretty->encode(\%query_results, {ascii => 1, pretty => 1});

问题是,我的数据集中的最后一项屏蔽了前面的所有项,因此我最终得到了一个包含相同确切数据的大型JSON。我想我可以使用一组散列,但这看起来真的很杂乱。如何编写最干净的代码来获取数据?如果哈希数组是最好的方法,请让我知道,我会这样做。我已经准备好知道如何或可以自己解决问题。

如果您尝试:

my $index = 0;
my %query_results;

while (my ($orderID, $possessorName, $itemDescription, $...) = $sth->fetchrow_array) {
    my %data = (orderID => $orderID, possessorName => $possessorName, itemDescription => $itemDescription,...);
    $query_results{"job$index"}{'data'} = \%data;
    $index++;
}
以前,您使用了在外部作用域中声明的
%data
哈希;更糟糕的是,你没有使用严格的
;使用警告
,因此
%数据
实际上是一个隐式全局变量。现在,我们在循环中声明
%data
,这使得所有散列都不同

您还可以通过
{%data}
将哈希复制到新的hashref中

也就是说,您甚至不需要该变量:

$query_results{"job$index"}{data} = {
  # anonymous hashref here
  orderID          => $orderId,
  possessorName    => $possessorName,
  itemDescription  => ...
};