1

I have a 2d array in 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. 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. Where did I go wrong?

2
  • regarding style, for(my $i = 0; $i <= $arrsize; $i++) is commonly written as for my $i (0 .. $#arr) for @arr array Commented Aug 12, 2013 at 10:31
  • Did you consider using PDL? Should make matrix operations very easy. Commented Aug 12, 2013 at 13:18

1 Answer 1

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

does not make sense as @translatematrix slurps all elements from @_, and should be:

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

where $translatematrix is array reference.

        $_ = $_ - $x;

should be more like

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

and also similar logic to $y and $z should be applied.

Sign up to request clarification or add additional context in comments.

2 Comments

This technique works, but it prevents me from using the current method of calculating length. How do I calculate length of the array?
@user2657817 you can change parameter order ie. my ($x, $y, $z, @translatematrix) = @_; so array is last one

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.