Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the 1st example gets different results than the following 2 in powershell

Tags:

powershell

$b = (2,3)

$myarray1 = @(,$b,$b)

$myarray1[0].length #this will be 1
$myarray1[1].length

$myarray2 = @(
,$b
,$b
)

$myarray2[0].length #this will be 2
$myarray[1].length

$myarray3 = @(,$b
,$b
)

$myarray3[0].length #this will be 2
$myarray3[1].length

UPDATE

I think on #powershell IRC we have worked it out, Here is another example that demonstrates the danger of breaking with the comma on the following line rather than the top line when listing multiple items in an array over multiple lines.

$b = (1..20)

$a = @( $b, $b ,$b,
        $b, $b ,$b)

for($i=0;$i -lt $a.length;$i++)
{
  $a[$i].length
}        
"--------"
$a = @( $b, $b ,$b
       ,$b, $b ,$b)

for($i=0;$i -lt $a.length;$i++)
{
  $a[$i].length
}        

produces

20
20
20
20
20
20
--------
20
20
20
1
20
20

In fact rather that using nested arrays that may complicate it here is a simple array of integers

$c = @( 1 , 2 , 
        3 , 4 )
for($i=0;$i -lt $c.length;$i++)
{
  $c[$i].gettype()
}        
"---------"
$c = @( 1 , 2 
       , 3 , 4 )
for($i=0;$i -lt $c.length;$i++)
{
  $c[$i].gettype()
}        

and the results

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

I'm curious how people will explain this. I think I understand it now, but would have trouble explaining it in a concise understandable fashion, though the above example goes somewhat towards that goal.

like image 857
klumsy Avatar asked Mar 13 '11 05:03

klumsy


1 Answers

I can explain the first example, but not the second two. The unary comma operator (see http://rkeithhill.wordpress.com/2007/09/24/effective-powershell-item-8-output-cardinality-scalars-collections-and-empty-sets-oh-my/) creates an array with one member, so ,$b creates an array containing ($b); ,$b,$b creates an array containing (,$b and $b).

The second two examples, I believe, are creating an array with one-element containing $b,$b. Then the one-element array gets flattened, yielding just $b,$b.

If somebody can post a link definitively explaining the behavior of the second two examples, I'd love to see it!

like image 157
Gabe Avatar answered Nov 02 '22 11:11

Gabe