please consider this example
if(-not $lang) {
$lang = $lol
if(-not $lang) {
$lang = $bar
if(-not $lang) {
write-host "do something"
$lang = 'PS+'
}
}
}
new syntax inspired from perl
$lang //= $lol // $bar // {
write-host "do something"
"PS+"
}
if $lang is not defined then $lang = $lol, if $lang is not defined then $lang = $bar if $lang is not defined then affect the result of scriptblock to $lang...in this case $lang = 'PS+' and print in console 'do something'
Given that PS comes from and occasionally borrows from c#, perhaps utilising the common 'if null' implied behaviour of ?
would be best here?
$lang ?= Value
It's worth defining defining what "defined" means in this context. In other words is it:
I think 3 is probably the most effective and most intuitive solution here.
@vexx32 I agree, though I'd like to see that handled with $var = $var ?? 'value if empty'
personally.
That syntax is great, but given how similar that is to $var = $var + 10
I can almost guarantee there would still be demand for the shorthand. :)
Though whether that ends up being $var ?= value
or $var ??= value
is up in the air, really.
Great idea, but this has already been proposed in the context of #3240, with ??
/ ?=
syntax.
I suggest we continue the conversation there.
Not quite as concise as //= (but much more so than the nested if
statements), you can use the -or
operator to do the following:
if (($lang = $lol) -or ($lang = $bar) -or ($lang = "default")) {
"lang is $lang"
}
Short-circuiting will stop execution at the first assignment that doesn't result in null.
Unfortunately, that's not enough for a true, general "if undefined/null" pattern, given that a strictly Boolean test would fail for _all_ "falsy" values, including 0
.
Accounting for that gets unwieldy:
$lol = 0
if ($null -ne ($lang = $lol) -or ($null -ne ($lang = $bar)) -or ($lang = "default")) {
"lang is $lang"
}
But let us continue the discussion in #3240 - or, syntax form aside, is there something here not covered in the other proposal?
Most helpful comment
Not quite as concise as //= (but much more so than the nested
if
statements), you can use the-or
operator to do the following:Short-circuiting will stop execution at the first assignment that doesn't result in null.