Repository navigation
Control statements in assignment RHS #231
Description
Activity
Hi Steve, thanks for reporting!
Do you know if those conditionals, loops, and exceptions are available in any arbitrary expression?
Like can I do this with a try/catch?
if (2 * try { Get-Thing } catch { 4 } -gt $sentinel )
{ echo Foo }The OP's pattern for if is seen in the official docs in Assignment Operators:
You can also assign the value created by a statement to a variable, as in the following example:
$a = if ($b -lt 0) { 0 } else { $b }This example assigns zero to the
$avariable if the value of$bis less than zero. It assigns the value of$bto$aif the value of$bisn't less than zero.
And as an example, not itself documented at foreach:
$filesToProcess = if ($_ -is [System.IO.FileSystemInfo]) {
$_
} else {
Get-Item -Path $Path
}I think I've found the real documentation for this at Statement values. These can get crazy:
$i = 1
$v = while ($i -le 5) {
$i # $i is written to the pipeline
if ($i -band 1) {
"odd" # conditionally written to the pipeline
}
++$i # not written to the pipeline
}
# $v is object[], Length 8, value 1,"odd",2,3,"odd",4,5,"odd"Does this mean that technically every statement is an expression? Including function and class definitions?
As usual, PowerShell is more complicated.
# legal, $foo is 4 (= 0 + 4)
$foo = try { Get-Thing } catch { 0 } + 4
# crashes
$foo = 4 + try { Get-Thing } catch { 0 }
# compiles, but unclear what $foo becomes
$foo = function Name { 5; Write-Host 6; return 7 }I think we move exceptions, loops, , and flowconditionals from statements to expressions-without-commands and let the user sort it out if they try to add 4 + try {....
Hi!
I noticed that syntax highlighting does not work properly for control statements used on the right-hand side of assignments.
I tried a small fix and for now it seems to work fine without unexpected side-effects.
My testing is limited, so I can't say anything definitive about edge cases or possible performance implications.
Here's my change:
I'm not opening this as a PR because I don't know how to write syntax tests, and I'm unsure if this needs to be implemented differently as a proper fix.
Thanks for your work!
Best Regards
Steve