Home > Back-end >  Can someone explain what this piece of code is doing?
Can someone explain what this piece of code is doing?

Time:12-02

This is code I found that splits an array into odd or even results.

$f=0; $array | % { if($f = !$f) { $_ } }

The part I don't understand is the if statement. Specifically $f=!$f.

The way I'm reading it is if(0 = not 0). The result should always be true since it's using = and not -eq. I'm sure it's something simple I'm missing, but I can't find any info on it.

If anyone has any good resources to read that goes further into this type of logic I'd also love to read more on it.

CodePudding user response:

It's showing every odd array element. $f goes back and forth from $true to $false. The value of the assignment is what's on the left side. I would start with $f = $false, to make it a little more clear.

!0
True

!$true
False

$array = 1..10
$f=0; $array | % { if($f = !$f) { $_ } }
1
3
5
7
9

CodePudding user response:

The = in the if() is an assignment, not a comparison (which would use -eq, as you noted). So, each pass through the ForEach-Object loop toggles the value of $f between $false and $true, and emits the passed value from the array when it’s $true. As written, it gives you the values in the even-numbered positions in the array (zero-origin). If you start with $f=1, it will give the values in the odd-numbered positions.

  • Related