Question:
I have an example of a program that creates an array, and then attempts to assign the value of that array multiple times into another array as a multidimensional array.
1 2 3 4 5 6 7 |
$a =@(0,0,0) $b = @($a,$a,$a) $b[1][2]=2 $b 'And $a is changed too:' $a |
The output is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
PS E:\Workarea> .\what.ps1 0 0 2 0 0 2 0 0 2 And $a is changed too: 0 0 2 |
So in this instance, the variable is actually pointing to the original variable. This is very unexpected behavior. It’s rather neat that one can do this, although I never did use unions that much in my C programming. But I’d like a way to actually just do the assignment of the value, not of the variable.
1 2 |
$b = @($a.clone(),$a.clone(),$a.clone()) |
I guess would work, but something tells me that there may be something a little more elegant than that.
Thanks for the input.
This is PowerShell 2.0 under Windows 7 64-bit.
Answer:
To assign the values of $a
to $b
instead of the reference to $a
, you can wrap the variable in $()
. Anything in $()
gets evaluated before using it in the command, so $($a)
is equivalent to 0, 0, 0
.
1 2 3 4 5 6 7 |
$a =@(0,0,0) $b = @($($a),$($a),$($a)) $b[1][2]=2 $b '$a is not changed.' $a |