http://www.perlmonks.org?node_id=1227852

in reply to Re^2: Array value changing for some reason
in thread Array value changing for some reason

Even though I don't understand what "for my \$i (0 .. \$#arr)"

\$#array is the index of the last element of @array. Which is the same as the scalar(@array)-1;

a subroutine can change variables from the function it was called from

Yes, if you modify @_, it changes for the caller.

• Comment on Re^3: Array value changing for some reason

Replies are listed 'Best First'.
Re^4: Array value changing for some reason
by jwkrahn (Monsignor) on Dec 31, 2018 at 20:23 UTC
\$#array is the index of the last element of @array. Which is the same as the scalar(@array)-1;

Depending on which version of perl and the value of \$[.     :)

Re^4: Array value changing for some reason
by Silt (Novice) on Jan 01, 2019 at 03:40 UTC
What I don't understand is why I get different results in this code:
```use strict;
use warnings;

problem([1,2,3]);

sub problem {
print2DArray(@_);  #Output: 1 2 3
reverseArray1(@_);
print2DArray(@_);  #Output: 1 2 3
reverseArray2(@_);
print2DArray(@_);  #Output: 3 2 1
}

sub reverseArray1 {
my @arr = @_;
for my \$i (0 .. \$#arr) {
\$arr[\$i] = [reverse @{\$arr[\$i]}];
}
}

sub reverseArray2 {
my @arr = @_;
for my \$i (0 .. \$#arr) {
@{\$arr[\$i]} = reverse @{\$arr[\$i]};
}
}

sub print2DArray {
for my \$i (0 .. \$#_) {  # How does that work for the nested for lo
+op?
for(my \$j=0;\$j<scalar(@{\$_[\$i]});\$j++){  # \$#_[\$i] doesn't wor
+k
print \$_[\$i][\$j]," ";
}
print "\n";
}
}
Whats the difference between
```\$arr[\$i] = [reverse @{\$arr[\$i]}];
and
```@{\$arr[\$i]} = reverse @{\$arr[\$i]};
?

I still am quite new to perl, and I appreciate all the comments!
\$arr[\$i] = [reverse @{\$arr[\$i]}];

assigns a new reference (by creating a new anonymous array) to \$arr[\$i] replacing the reference copied from @_. Without that reference you can't change the contents of @_

Whereas @{\$arr[\$i]} = reverse @{\$arr[\$i]} uses the reference copied from @_ to change the existing array elements.

`# \$#_[\$i] doesn't work`
```sub print2DArray {
for my \$i (0 .. \$#_) {
for my \$j (0 .. \$#{\$_[\$i]}){
print \$_[\$i][\$j]," ";
}
print "\n";
}
}
```sub print2DArray7 {