Powershell: new operator // (if not defined)

Created on 17 Oct 2018  路  8Comments  路  Source: PowerShell/PowerShell

please consider this example

Steps to reproduce

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'

Issue-Discussion WG-Language

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:

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.

All 8 comments

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:

  1. The variable hasn't been set in the current scope
  2. The variable hasn't been set in the current scope and has not been inherited from a previous scope (true "not defined")
  3. Any of the above or the variable has been set but is null or empty

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?

Was this page helpful?
0 / 5 - 0 ratings