On Sun, Oct 16, 2011 at 01:08:19AM +0200, JPH wrote:
> Hi all,
>
> I am passin a two-dimensional array to a sub and when the sub
This is your main problem. Perl doesn't have two-dimensional arrays. What it
does have is arrays of array references which, if you squint, can be used as
two-dimensional arrays. And this is what you have here. Armed with this
knowledge, perhaps you can already see the problem and solution.
> returns, the original array has changed. Eventually I want to pass
> the array into a recursive sub, so I want to find a way to
> circumvent this behaviour. Notice how my global is "@a" and the sub
> local is "@b"
> - Why is this happening
> - How can I properly pass a two dimensional array to a sub, without the array
> in main changing?
>
> Ideas anyone?
When call try(), (or more accurately, when you assign to @b) you are
performing a shallow copy of the array. It seems that you really need a deep
copy. You could either explicity write this yourself, or you could use
something such as dclone in Storable.
> Here is the minimal script to reproduce my finding:
> =============
> #!/usr/bin/perl
>
> use warnings;
> use strict;
>
> sub try {
> my @b = @_;
> $b[ 0 ][ 1 ] = "7";
> return 3;
> }
>
> my @a;
> $a[ 0 ][ 1 ] = " ";
>
> print "Before: " . $a[ 0 ][ 1 ] . "\n";
> try( @a );
> print "After: " . $a[ 0 ][ 1 ] . "\n";
>
> exit;
> =============
> What happens:
> Before:
> After: 7
> =============
> What I would expect:
> Before:
> After: 0
> =============
--
Paul Johnson - [email protected]
http://www.pjcj.net
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/