gpt4 book ai didi

Powershell 'x or y' 分配

转载 作者:行者123 更新时间:2023-12-04 02:01:12 26 4
gpt4 key购买 nike

有几种语言提供默认或逻辑或分配机制:

a = b || c;
a = b or c
a="${b:-$c}"
a = b ? b : c;

到目前为止,我在 Powershell Core 中发现的唯一等效项是极其冗长的:
$a = if ($b) { $b } else { $c }

在某些情况下必须成为
$a = if ($b -ne $null) { $b } else { $c }

有没有更好的选择 [编辑:] 不牺牲可读性?

最佳答案

没有 || PowerShell 赋值中的短路运算符,与 Perl 的 // 没有任何相同之处“定义或”运算符 - 但您可以构造一个简单的 null coalesce像这样模仿:

function ?? {
param(
[Parameter(Mandatory=$true,ValueFromRemainingArguments=$true,Position=0)]
[psobject[]]$InputObject,

[switch]$Truthy
)

foreach($object in $InputObject){
if($Truthy -and $object){
return $object
}
elseif($object -ne $null){
return $object
}
}
}

然后使用像:
$a = ?? $b $c

或者,如果您只想返回任何评估为 $true 的内容就像你的第一个例子:
$a = ?? $b $c -Truthy

关于Powershell 'x or y' 分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51508233/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com