So I was trying to write a simple recursive function to create permutations of a set. It creates an array of hash tables - each table being one permutation. I ran a quick test - worked!
Then, I stored the result in a variable, and now it doesn't work anymore. All the rows in the result variable are the same as the expected last row.
Why is the result different when stored in a variable? Is this a powershell bug due to some optimization?
function simple($data, $index)
{
if ($index -lt 0) {
$data.count = $global:count
$global:count = $global:count + 1
$data ### This is the return value
} else {
$name = "Name_$index"
$data.$name = $index + 100
simple $data ($index - 1)
$data.$name = $index + 200
simple $data ($index - 1)
}
}
# Case1: Just let the results print - works as expected
$global:count = 0
$d = [ordered]@{Count = -1; Name_0 = -1; Name_1 = -1}
Write-Output "Case 1: Show return value"
simple $d 1
# Case2: Just let the results print - works as expected
$global:count = 0
$d = [ordered]@{Count = -1; Name_0 = -1; Name_1 = -1}
Write-Output "Case 2: Store then show return value"
$a = simple $d 1
$a
The results are:
Case 1: Show return value
Name Value
---- -----
count 0
Name_0 100
Name_1 101
count 1
Name_0 200
Name_1 101
count 2
Name_0 100
Name_1 201
count 3
Name_0 200
Name_1 201
Case 2: Store then show return value
count 3
Name_0 200
Name_1 201
count 3
Name_0 200
Name_1 201
count 3
Name_0 200
Name_1 201
count 3
Name_0 200
Name_1 201