3

I noticed a difference between those two declarations where only the position of the comma changes:

$a = @( @('a','b'),
        @('c','d'))

$b = @( @('a','b')
      , @('c','d'))

In this case, $a.length evaluates to 2 and $b.length evaluates to 3. The first sub-array of $b has been flattened.

Is this a feature and where can I find its documentation?

By the way, $PSVersionTable:

Name                           Value
----                           -----
PSVersion                      4.0
WSManStackVersion              3.0
SerializationVersion           1.1.0.1
CLRVersion                     4.0.30319.42000
BuildVersion                   6.3.9600.16406
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0}
PSRemotingProtocolVersion      2.2
Benoit
  • 76,634
  • 23
  • 210
  • 236

1 Answers1

2
 , Comma operator
         As a binary operator, the comma creates an array. As a unary
         operator, the comma creates an array with one member. Place the
         comma before the member.

Source.

Its because @('a','b') will push two strings a and b into the array $b whereas you force @('c','d')to get pushed into $b as an array using a comma.

Example:

$b = @( @('a','b')
      , @('c','d'))

$b | foreach { Write-Host "Item: $_"}

Output:

Item: a
Item: b
Item: c d

And if you look at the types:

$b | foreach { $_.GetType()}

You get:

IsPublic IsSerial Name     BaseType     
-------- -------- ----     --------     
True     True     String   System.Object
True     True     String   System.Object
True     True     Object[] System.Array 

To force $b to contain two arrays, use the comma binary operator:

$b = @(@('a','b'),@('c','d'))
Martin Brandl
  • 56,134
  • 13
  • 133
  • 172
  • I am sorry, I don't understand your answer. `$b = @(@('a','b'),@('c','d'))` contains two arrays without comma. What is the difference when I insert newline BEFORE the comma and AFTER the comma? – Benoit Jun 09 '16 at 09:35
  • You are right. Its because in this case the `comma` is used as a binary operator, see my edit. – Martin Brandl Jun 09 '16 at 09:40
  • Does that mean binary operators cannot follow newline? – Benoit Jun 09 '16 at 09:44
  • Yes it does. You can validate that if you adding a backtick ` to the end of the first line, then the comma is treated as a binary operator – Martin Brandl Jun 09 '16 at 09:50