为什么它需要一对额外的支架? [英] Why it needs an extra pair of bracket?

查看:32
本文介绍了为什么它需要一对额外的支架?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的powershell脚本

一"、二"、三" |% { "$(($l++)): $_" }

将打印

<前>1:一个2:两个3:三个

然而,在去掉$l++

周围的括号后

一"、二"、三" |% { "$($l++): $_" }

它会打印

<前>: 一: 二: 三

解决方案

这是因为 $l++ 是一个 可撤销语句.在 powershell 中,某些类型的表达式,当用作语句时,不显示.Voidable 语句包括赋值和递增/递减运算符.当它们在表达式中使用时,它们返回一个值,但当它们用作独立语句时,它们不返回任何值.Bruce PayetteWindows Powershell in Action 中很好地解释了这一点:

<块引用>

PowerShell 中几乎不包含递增和递减运算符因为他们引入了一个问题.在 C 和 C# 等语言中,当您使用这些运算符之一作为声明:$a++什么都没有显示.这是因为 C 和 C# 中的语句不返回值.在但是,在 PowerShell 中,所有语句都返回一个值.这导致了混乱.人们会写这样的脚本:

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

<块引用>

并惊讶地看到显示的数字 1 到 10.这是因为 $a++返回一个值,PowerShell 显示每个语句的结果.这太令人困惑了,我们几乎从语言中删除了这些运算符.然后我们想到了可作废声明的想法.基本上,这意味着某些类型的表达式,当用作语句时,不显示.可作废的陈述包括赋值和递增/递减运算符.当它们用于表达式,它们返回一个值,但是当它们用作独立语句时,它们不返回任何值.同样,这是不会影响您使用 PowerShell 的方式的细节之一,只是让它按您的预期工作.(来源:Windows Powershell 实战)

The following powershell script

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

will print

1: one
2: two
3: three

However, after remove the bracket around $l++

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

it will print

: one
: two
: three

解决方案

This is because $l++ is a voidable statement. In powershell 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. It is very well explained in Windows Powershell in Action by Bruce Payette:

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)

这篇关于为什么它需要一对额外的支架?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆