in reply to Array value changing for some reason
@_ is an array of aliases to the actual arguments, so changing @_ changes the actual arguments.
sub { ++$_ for @_ }->(my @arr = 'a' .. 'c'); print "@arr"; # Output: b c d
In your case, it's bit more complex. Changing the function to
wouldn't have helped, as you're working with an array of arrays. The inner arrays are represented as references, so even if you store the references in a different @arr, they still refer to the same inner arrays.sub reverseArray { my @arr = @_; for my $i (0 .. $#arr) { @{ $arr[$i] } = reverse @{ $arr[$i] }; } }
To keep the array unchanged, only assign to the copy, don't change the references from the original array.
sub reverseArray { my @arr = @_; for my $i (0 .. $#arr) { $arr[$i] = [ reverse @{ $arr[$i] } ]; } }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Array value changing for some reason
by Silt (Novice) on Dec 31, 2018 at 23:23 UTC | |
by kschwab (Vicar) on Dec 31, 2018 at 23:37 UTC | |
by jwkrahn (Abbot) on Jan 01, 2019 at 02:23 UTC | |
by Silt (Novice) on Jan 01, 2019 at 09:40 UTC | |
by poj (Abbot) on Jan 01, 2019 at 16:34 UTC | |
by AnomalousMonk (Archbishop) on Jan 01, 2019 at 00:56 UTC |