Perl: the Markov chain saw PerlMonks

### Re^4: Array value changing for some reason

by Silt (Novice)
 on Jan 01, 2019 at 09:40 UTC ( #1227860=note: print w/replies, xml ) Need Help??

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

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!

Replies are listed 'Best First'.
Re^5: Array value changing for some reason
by poj (Abbot) on Jan 01, 2019 at 16:34 UTC
\$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";
}
}
or
```sub print2DArray7 {
for (@_) {
print join " ",@\$_;
print "\n";
}
}
poj

Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1227860]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (6)
As of 2022-11-29 21:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
My favourite new Perl feature (in 2022) ...

Results (42 votes). Check out past polls.

Notices?