如何拼接数组哈希中的数组



我正在填充这样的数据结构:-

push @{$AvailTrackLocsTop{$VLayerName}}, $CurrentTrackLoc;

其中$VLayerName是 m1、m2、m3 等字符串,$CurrentTrackLoc只是一个十进制数。如果我使用 Data::D umper 在完全填充哈希后打印哈希的内容,它会显示我的期望,例如:-

$VAR1 = {
      'm11' => [
                 '0.228',
                 '0.316',
                 '0.402',
                 '0.576',
                 '0.750',
                 '569.458',
                 '569.544',
                 '569.718',
                 '569.892'
               ]
    };

现在我需要有效地拼接存储的十进制数字列表。我可以删除这样的条目:-

for (my $i = $c; $i <= $endc; $i++) {
    delete $AvailTrackLocsTop{$VLayerName}->[$i];
}

正如预期的那样,结果是一堆"undef"条目,其中曾经存在数字,例如:-

$VAR1 = {
      'm11' => [
                 undef,
                 undef,
                 undef,
                 undef,
                 '0.750',
                 '569.458',
                 '569.544',
                 '569.718',
                 '569.892'
               ]
    };

但是我怎样才能清除 undef 条目,以便我看到这样的东西呢?

$VAR1 = {
      'm11' => [
                 '0.750',
                 '569.458',
                 '569.544',
                 '569.718',
                 '569.892'
               ]
    };

重要的是要注意,删除可以在数组中的任何位置,例如索引 33 和 99 of 100。在哈希结构的上下文之外拼接数组很容易,但是当数组嵌入到大哈希中时,我正在努力操作数组。

首先,我想从删除文档中注意:

WARNING: Calling delete on array values is strongly discouraged. The notion of deleting or checking the existence of Perl array elements is not conceptually coherent, and can lead to surprising behavior.

将数组元素设置为 undef 的正确方法是使用 undef 函数(或只是为其分配 undef(。

要删除元素,您可以使用 splice 函数,它在嵌套 arrayrefs 上的工作方式与在普通数组上的工作方式相同,您只需要像对 push 一样取消引用它。

splice @{$AvailTrackLocsTop{$VLayerName}}, $c, $endc - $c + 1;

考虑到您所处的位置,最简单的方法可能是在没有 undefs 的情况下重建数组:

$_ = [ grep defined, @$_ ] for values %AvailTrackLocsTop;
或者,您可以拥有哈希的哈希,而不是

数组的哈希,然后删除将导致它们消失,而无需简单地转向 undef。如果这很重要,你只会失去订单。

最新更新