Our
Our

Reputation: 1035

Why are the referenced array's values not changed?

I'm trying to multiply the each component of an array with a scalar, and to do this, have tried the followings;

1-)

@foo = (1, 2, 3, 5, 6);
vectorScalarMultiply(\@foo);
print @foo, "\n";

sub vectorScalarMultiply
{
    my $l_vectorRef = $_[0];
    for (my $var = 0; $var < scalar(@temp); $var++) {
        $l_vectorRef->[$var] = $l_vectorRef->[$var] * 5;
    }
}

1's Output;

12356

2-)

@foo = (1, 2, 3, 5, 6);
vectorScalarMultiply(\@foo);
print @foo, "\n";
sub vectorScalarMultiply
{

    my $l_vectorRef = $_[0];
    map { $l_vectorRef->[$_] * 5 } { $l_vectorRef->[$_] };
}

2's Output;

123456

3-)

@foo = (1, 2, 3, 5, 6);
@temp = @{$l_vectorRef};
vectorScalarMultiply(\@foo);
print @foo, "\n";
$l_vectorRef = map { $temp[$_] * 5; } @temp;

3's Output;

12356

And I haven't been able to figure out what is the problem, and why are they not working, so my main question is that what is the problem with these code ?Secondly, how can we solve it ?

Upvotes: 2

Views: 92

Answers (2)

hobbs
hobbs

Reputation: 240010

The first one doesn't work because your loop condition is $var < scalar(@temp), but there is no @temp, so the loop never executes.

The second one doesn't work because map doesn't modify anything, and you're not assigning the result of the map to anything.

The third one doesn't work because you're modifying the variable $l_vectorRef inside the sub, and not modifying the array that that variable holds a reference to.

Here is a more idiomatic working version:

sub vectorScalarMultiply {
    my ($aref) = @_;
    $_ *= 5 for @$aref;
}

Upvotes: 7

Quentin
Quentin

Reputation: 943645

  1. Because you forgot use strict; use warnings; so didn't notice that @temp is undefined so your loop length is 0.
  2. Because you forgot use strict; use warnings; so didn't notice that map { $l_vectorRef->[$_] * 5 } { $l_vectorRef->[$_] }; expects the { $l_vectorRef->[$_] } to be a list. You also didn't assign the result of the map anywhere.
  3. Because you forgot use strict; use warnings; so didn't notice that you never defined $l_vectorRef (but if you did, then the map would overwrite the reference and not replace the original array)

Upvotes: 7

Related Questions