我正在学习用PowerShell编写脚本,我发现这段代码将帮助我完成一个项目--示例来自是否有一个一行用于使用默认值与读-主机?。
$defaultValue = 'default'
$prompt = Read-Host "Press enter to accept the default [$($defaultValue)]"
$prompt = ($defaultValue,$prompt)[[bool]$prompt]
我想我理解$prompt = ($defaultValue,$prompt)
正在创建一个双元素数组,并且[bool]
部分强制$prompt
数据类型为布尔值,但我不理解第三行代码作为一个整体所做的事情。
发布于 2016-11-30 15:44:05
这是一种常见的编程模式:
if (user entered a price)
{
price = user entered value
}
else
{
price = default value
}
因为这很常见,而且也很长,有些语言有一个特殊的ternary operator
,可以更简洁地编写所有的代码,并在一次移动中将一个变量赋给“这个值或那个值”。例如,在C#中,您可以编写:
price = (user entered a price) ? (user entered value) : (default value)
# var = IF [boolean test] ? THEN (x) ELSE (y)
如果测试为真,?
将分配(x)
,如果测试为false,则分配(y)
。
在Python中,它被写成:
price = (user entered value) if (user entered a price) else (default value)
在PowerShell中,它被写成:
# you can't have a ternary operator in PowerShell, because reasons.
嗯。不允许使用很好的短代码模式。
但是,你可以做的是滥用数组索引(@('x', 'y')[0] is 'x'
和@('x', 'y')[1] is 'y'
),并编写丑陋和混乱的代码-高尔夫行:
$price = ($defaultValue,$userValue)[[bool]$UserEnteredPrice]
# var (x,y) is an array $array[ ] is array indexing
(0,1) are the array indexes of the two values
[bool]$UserEnteredPrice casts the 'test' part to a True/False value
[True/False] used as indexes into an array indexing makes no sense
so they implicitly cast to integers, and become 0/1
# so if the test is true, the $UserValue is assigned to $price, and if the test fails, the $DefaultValue is assigned to price.
它的行为就像一个三值运算符,只不过它令人困惑和丑陋,而且在某些情况下,如果您不小心计算这两个数组表达式,不管选择哪个数组表达式(与实际的?
运算符不同),都会让您感到困惑。
编辑:我真正应该添加的是我喜欢的PowerShell表单--您可以在PowerShell中直接分配if
测试的结果,然后执行:
$price = if ($userValue) { $userValue } else { $DefaultValue }
# ->
$prompt = if ($prompt) { $prompt } else { $DefaultValue }
https://stackoverflow.com/questions/40892156
复制相似问题