Fellow Lab49er Daniel Simon asked why the different results?
PS > $a=1,(2,3) PS > $a.Count 2 PS > ($a | % {$_}).count 3
What do you think?
Researching the optimal; implementing the practical
Fellow Lab49er Daniel Simon asked why the different results?
PS > $a=1,(2,3) PS > $a.Count 2 PS > ($a | % {$_}).count 3
What do you think?
{ 4 comments… read them below or add one }
I believe it is because PowerShell “flattens” arrays when sending them down the pipeline, so you end up with all three elements in the second case.
a is an array with a value of 1 and an array with the numbers 2 and 3
so it has two items
when you pipe it to a for each (%) you are with () so essentially you are creating a new array with the values 1,2,3 so hence the new count of the anonymous array is 3
To paraphrase Steven: If the rule is:
‘Send to pipe’ on an array (or enumerable) means send down the pipe its elements separately (i.e. ‘flatten’).
First, per the rule, “$a |” sends two elements down: 1 and then (2,3). Then “%{…}” will process both as simply ’send to the pipe’ again (which is what “$_” does) which means do ’send to pipe’ on “1″ and then ’send to pipe’ on “(2,3)”. Send to pipe on “(2,3)” means to send 2 and 3 separately according to the rule again. So three things end up in all (before being wrapped as an output and told to .count).
yep..
it’s because “1″ and “(2,3)” represent 2 objects: “1″ is int32 and “(2,3)” is the array
in the other hand, when you use foreach loop, you are working with whole pipeline input, which, actually, contains 3 objects together