gpt4 book ai didi

powershell - 为什么需要额外的一对支架?

转载 作者:行者123 更新时间:2023-12-04 13:17:23 25 4
gpt4 key购买 nike

以下powershell脚本

"one","two","three" | % { "$(($l++)): $_" }

将打印
1: one2: two3: three

However, after remove the bracket around $l++

"one","two","three" | % { "$($l++): $_" }

它将打印

: 一
: 二
: 三

最佳答案

这是因为$l++可空声明。在Powershell中,某些类型的
当用作语句时,不显示表达式。
无效的语句包括赋值和增量/减量运算符。在表达式中使用它们时,它们将返回一个值,但是在用作独立语句时,它们将不返回任何值。这在Bruce Payette的《 Windows Powershell in Action》中得到了很好的解释:

The increment and decrement operators were almost not included in PowerShell because they introduced a problem. In languages such as C and C#, when you use one of these operators as a statement: $a++ nothing is displayed. This is because statements in C and C# don’t return values. In PowerShell, however, all statements return a value. This led to confusion. People would write scripts like this:


$sum=0
$i=0
while ($i -lt 10) { $sum += $i; $i++ }
$sum

and be surprised to see the numbers 1 through 10 displayed. This was because $a++ returned a value and PowerShell was displaying the results of every statement. This was so confusing that we almost removed these operators from the language. Then we hit on the idea of a voidable statement. Basically, this means that certain types of expressions, when used as statements, are not displayed. Voidable statements include assignments and the increment/decrement operators. When they are used in an expression, they return a value, but when they’re used as a standalone statement, they return no value. Again, this is one of those details that won’t affect how you use PowerShell other than to make it work as you expect. (source: Windows Powershell in Action)

关于powershell - 为什么需要额外的一对支架?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8978954/

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