【问题标题】:How to splice an array that is in a hash of arrays?如何拼接位于数组哈希中的数组?
【发布时间】:2019-06-07 03:28:12
【问题描述】:

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

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

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

$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。在散列结构的上下文之外拼接数组很容易,但是当数组嵌入到大散列中时,我很难操作它。

【问题讨论】:

    标签: perl


    【解决方案1】:

    首先,我想从delete 文档中指出:

    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 函数,它在嵌套数组引用上的工作方式与在普通数组上的工作方式相同,您只需像对 push 所做的那样取消引用它。

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

    【讨论】:

    • 谢谢,@Grinnz——这正是我所需要的。我没有意识到嵌套数组引用可以如此干净地操作。也感谢您对删除操作的提醒......
    【解决方案2】:

    可能最简单的方法是在没有 undef 的情况下重建数组:

    $_ = [ grep defined, @$_ ] for values %AvailTrackLocsTop;
    

    或者,您可以使用散列散列而不是数组散列,然后删除将导致它们消失,而无需简单地转向 undef。如果这很重要,您只会失去订单。

    【讨论】:

      猜你喜欢
      • 2011-04-20
      • 2012-06-19
      • 2019-04-19
      • 2020-07-24
      • 2016-03-30
      • 2011-09-01
      • 2011-07-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多