简体   繁体   English

2d数组:更改元素Perl

[英]2d Array: Changing Elements Perl

I have a 2d array in Perl. 我在Perl中有一个二维数组。 I passed the array to a subroutine and I want to modify all elements of the 2d array then return it and print the array. 我将数组传递给子例程,我想修改2d数组的所有元素,然后返回它并打印该数组。 I have attached my code so far below. 到目前为止,我已经附加了我的代码。 The problem I am having is actually changing each individual element and passing the array to a subroutine. 我遇到的问题实际上是更改每个单独的元素并将数组传递给子例程。

Original Matrix+Code 原始矩阵+代码

       x            y       z
CG  -3.74900 -4.89100 -3.45400 
OD1 -6.45900 -6.29100 -6.08000 
OD2 -1.31600 -1.83300 -0.17600   

sub translateMatrixOperation
{
my (@translatematrix, $x, $y, $z) = @_;
print "PRINTING FIRST\n";
my $arrsize = scalar @translatematrix;
for(my $i = 0; $i <= $arrsize; $i++)
{
    for(my $j = 0; $j <= $arrsize; $j++)
    {
        if ($j == 0)
        {
            print "[$i][$j]:$translatematrix[$i][$j]\n";
            $_ = $_ - $x;
        }
        elsif ($j == 1)
        {
            print "[$i][$j]:$translatematrix[$i][$j]\n";
           $_ = $_ - $y;
        }
        elsif ($j == 2)
        {
            print "[$i][$j]:$translatematrix[$i][$j]\n";
            $_ = $_ - $z;
        }
    }
}
print "PRINTING\n";
for(my $i = 0; $i <= $arrsize; $i++)
{
    for(my $j = 0; $j <= $arrsize; $j++)
    {
        print "$translatematrix[$i][$j] ";
    }
    print "\n";
}
# return (\@translatematrix);

} I want to edit the whole array by adding a constant value to the x values, a constant value to the y values, and a constant to the z. 我想通过向x值添加一个常量值,向y值添加一个常量值以及向z添加一个常量来编辑整个数组。 Where did I go wrong? 我哪里做错了?

my (@translatematrix, $x, $y, $z) = @_;

does not make sense as @translatematrix slurps all elements from @_ , and should be: @translatematrix吞噬@_所有元素是没有意义的,应该是:

my ($translatematrix, $x, $y, $z) = @_;

where $translatematrix is array reference. 其中$translatematrix是数组引用。

        $_ = $_ - $x;

should be more like 应该更像

$translatematrix->[$i][$j] -= $x;

and also similar logic to $y and $z should be applied. 并应采用与$y$z类似的逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM