Andy Bryant has some ActionScript Puzzlers over here. So, let’s try them in PowerShell.
So the question is what does the call to loopy() return?
The answer is BEE,BOP,BOP,BOO. The extra BOP is the same result as the ActionScript and the same reason:
Although it appears that
capsis defined only within the for loop, it is actually defined at the scope of the function. Therefore for the secondnullin the array,capswas not overwritten, but instead retained its value from the previous iteration of the loop.
Function loopy { $names = $null, "bee", "bop", $null, "boo" $result = @() $names | % { if($_) { $caps = $_.ToUpper() } if($caps) { $result+=$caps } } $result -join "," } loopy
Good stuff. Hope to get more time to check out the other puzzles. If you add $caps = “” before the first if statement the extra BOP is solved.
{ 3 comments… read them below or add one }
This looked suspiciously like a quick ‘zip’ function I wrote last night so I tried to see if the issue applied to my logic. It doesn’t act exactly the same but is still odd. Here is a sample:
——-
function loopy2
{
$names = “abc”,”def”
$names2 = “def”,”ghi”
$result = @()
$names2 | ForEach-Object {
$name = $_
$f = $names | ?{ $_ -eq $name }
if ($f) { $result += $f.ToUpper() }
else { $result += $f }
}
$result.count
}
——-
I output the count property of the array because if it worked correctly you’d expect one item in the array, but really there ends up being two. However the second value is empty string or $null or something, not “def” as you might expect from the puzzle results.
I believe the second time thru when searching for $name and the value is not found, $f is -eq $null. This gets appended to your $result array, causing the count ot be 2.
You can check it like this: $result[1] -eq $null
I see, in your example you don’t have an else statement when checking for existence of $caps. Since I have the else something gets added to $result in any case.