【问题标题】:Perl add column to an arrayPerl 将列添加到数组
【发布时间】:2017-12-28 13:41:48
【问题描述】:

以下数组是数据库查询的结果,我想在 Perl 中添加一列:

<snip>
foreach my $array_ref ( @stash ) {
    print "@$array_ref\n";
}
<snip>

输出结果:

bash-3.2$ ./test.pl
2014 2 1
2015 2 1
2016 2 1
2017 1 0.5
bash-3.2$

我设法在底部添加一行。例如通过以下代码:

my @stashSum = ['Sum',  $sumNumDiv, $sumDiv];
push (@stash, @stashSum);

这会导致以下结果:

bash-3.2$ ./test.pl
2014 2 1
2015 2 1
2016 2 1
2017 1 0.5
Sum  7 3.5
bash-3.2$

我正在搜索将以下内容作为列添加到原始数组的代码:

my $i=0;
foreach my $array_ref ( @stash ) {
    $totalDiv[$i] = $array_ref->[2] * 15;
    print "$totalDiv[$i] \n";   
}

预期结果如下:

bash-3.2$ ./test.pl
2014 2 1 15
2015 2 1 15
2016 2 1 15
2017 1 0.5 7.5
bash-3.2$

有没有办法以与行类似的方式将列“推送”到数组中?如果没有,在 Perl 中如何将列添加到数组中?

【问题讨论】:

  • foreach my $array_ref ( @stash ) { push @$array_ref, "new_column" }
  • 感谢工作出色!!

标签: perl


【解决方案1】:

您似乎拥有的是对匿名数组的引用数组,您使用矩阵术语来引用这些数组,其中列指代这些匿名数组的元素,行是匿名数组本身。

因此,添加一列涉及在正确的位置预先添加、插入或附加另一个条目来操作这些数组中的每一个。 splice 对这类事情很有帮助。

#!/usr/bin/env perl

use strict;
use warnings;

use Test::More;

my $x = [ [1], [2] ]; # Two rows, single column

my @tests = (
    [ sub { push_column($x, 3) },    [     [1,3], [2,3]     ] ],
    [ sub { unshift_column($x, 4) }, [   [4,1,3], [4,2,3]   ] ],
    [ sub { add_column($x, 5, 1) },  [ [4,5,1,3], [4,5,2,3] ] ],
);

for my $case ( @tests ) {
    $case->[0]->();
    is_deeply $x, $case->[1];
}

sub add_column {
    my ($matrix, $v, $col) = @_;
    for my $r ( @$matrix ) {
        splice @$r, $col, 0, $v;
    }
    return;
}

sub push_column {
    add_column(@_, scalar @{ $x->[0] });
    return;
}

sub unshift_column {
    add_column(@_, 0);
    return;
}


done_testing;

【讨论】:

  • 谢谢!我仍在努力为@stash 添加一列。例如,我生成一个编号列:
  • if (@stash) { for $i (1..$rowsDiv){ my $n=$i-1; $Div[$n]=$i; } }
  • 预期结果如下:
  • bash-3.2$ ./test.pl 1 2014 2 1 15 2 2015 2 1 15 3 2016 2 1 15 4 2017 1 0.5 7.5 bash-3.2$
猜你喜欢
  • 2017-01-04
  • 2020-06-30
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 2014-03-05
  • 2021-12-27
  • 2019-04-22
  • 1970-01-01
相关资源
最近更新 更多