Why do some arrays reflect each other in Powershell

I am using Powershell 2.0. When I create a new variable as an array and then set another variable equal to the first, the second variable β€œmirrors” the first. After changing an object in the original array, the same change appears in the second array. For instance,

$array0001=6,7,3,4,0 $array0002=$array0001 $array0001[3]=55 $array0002 

with exit

 6 7 3 55 0 

I notice that when you set the second variable equal to the value of the first variable, with the exception of this time enclosed inside the subexpression operator, modifications to the first array do not affect the second array. For instance,

 $array0001=6,7,3,4,0 $array0002=$($array0001) $array0001[3]=55 $array0002 

with exit

 6 7 3 4 0 

Why does including a value in a subexpression statement change the behavior of a variable? Is there any other or better way to prevent the array variables from mirroring each other?

ETA: I found that $array0002=@ ($array0001) and $array0002=&{$array0001} fulfill the same goal.

+5
source share
2 answers

It is called "pass by reference". Instead of actually assigning a value, you assign a link to another location that contains the value. If the value in the source location changes, the link you made points to that source location and will see the updated value.

Most languages ​​have ways to "pass by reference" and "pass by value." This is what you found by doing $array0002=$($array0001) . None of them are better than the other, they both have different uses.

In PowerShell, you can also put .value behind your link to get the value instead of the link.

+7
source

When installing one array equal to another, different variables simply refer to each other, this is not a real copy. This is essentially the same thing you are asking for. From this link, serializing data to make a deep copy is a good way around it.

 #Original data $Array1 # Serialize and Deserialize data using BinaryFormatter $ms = New-Object System.IO.MemoryStream $bf = New-Object System.Runtime.Serialization.Formatters.Binary.BinaryFormatter $bf.Serialize($ms, $Array1) $ms.Position = 0 #Deep copied data $Array2 = $bf.Deserialize($ms) $ms.Close() 
+2
source

Source: https://habr.com/ru/post/1268674/


All Articles