Where is PowerShell's special array head/tail assignment documented?
Asked Answered
Z

1

6

I only just noticed that this is valid PowerShell code:

PS> $first, $rest = @(1, 2, 3)

This statement puts the first item in the array in $first and the remaining items in $rest.

PS> $first
1

PS> $rest
2
3

It even works for an arbitrary number of variables, pushing the current head into the next variable and the tail into the last one. You can try that for yourself.

PS> $first, $second, $rest = @(1, 2, 3, 4)

It seems to assign a $null value if there aren't enough heads or tails to put into one of the variables. Even in the case of the $rest (I'd rather have seen an empty array, but whatever).

PS> $first, $second, $rest = @(1)

PS> $first
1

PS> $second

PS> $second -eq $null
True

PS> $rest

PS> $rest -eq $null
True

PS> $rest -eq @()
False

The problem, and my question, is that I don't see this documented anywhere! I'm trying to find out when this was supported. Exactly how it's implemented. If it works for any other types.

I checked about_Assignment, about_Arrays, and about_Splatting, without any luck.

Zsolway answered 9/6, 2016 at 18:35 Comment(0)
H
6

See the following section near the bottom of about_Assignment_Operators...

Assigning multiple variables

In PowerShell, you can assign values to multiple variables by using a single command. The first element of the assignment value is assigned to the first variable, the second element is assigned to the second variable, the third element to the third variable, and so on. This is known as multiple assignment.

Homogony answered 9/6, 2016 at 18:40 Comment(1)
Oh no! I was searching on the page and not scrolling. Used some different terminology! What a goof :)Zsolway

© 2022 - 2024 — McMap. All rights reserved.