() 和 $() 的区别 [英] Difference between () and $()
问题描述
有什么区别
Write-Host (Get-Date) # just paren
和
Write-Host $(Get-Date) # dollar-paren
括号内的内容可以是任何内容,只是举一个简单的例子.两者有区别吗?
Content within the parens could be anything, just going with a simple example. Is there any difference between the two?
我认为自己在 PS 方面的经验相当丰富,但正是这些小事情让我感到困扰,尤其是在代码审查等过程中.有没有人找到这就是语言的工作原理"的良好来源,其中包含足够详细的信息来推导出此类问题的答案?
I consider myself reasonably experienced with PS, but it's these little things that bug me, especially during code review and the like. Has anyone come across a good source for "here is how the language works" with enough detail to derive answers to these sorts of questions?
推荐答案
子表达式 ($(...)
) 包含一个 StatementBlockAst
.它可以采用任意数量的语句,意思是关键字(if
、foreach
等)、管道、命令等.解析类似于在像 begin
/process
/end
这样的命名块内.
The sub expression ($(...)
) contains a StatementBlockAst
. It can take any number of statements, meaning keywords (if
, foreach
, etc), pipelines, commands, etc. Parsing is similar to the inside of a named block like begin
/process
/end
.
paren 表达式 ((...)
) 可以包含一个 single ExpressionAst
,它是 AST 的一个有限子集.语句和表达式之间最显着的区别是不解析关键字.
The paren expression ((...)
) can contain a single ExpressionAst
which is a limited subset of the AST. The most notable difference between a statement and an expression is that keywords are not parsed.
$(if ($true) { 'It worked!' })
# It worked!
(if ($true) { 'It worked!' })
# if : The term 'if' is not recognized as the name of a cmdlet, function,
# script file, or operable program. Check the spelling of the name, or
# if a path was included, verify that the path is correct and try again.
# At line:1 char:2
# + (if ($true) { 'It worked' })
# + ~~
# + CategoryInfo : ObjectNotFound: (if:String) [], CommandNotFoundException
# + FullyQualifiedErrorId : CommandNotFoundException
正如其他人所指出的,子表达式将在双引号字符串中展开.
Also as others have noted, the sub expression will expand in double quoted strings.
这篇关于() 和 $() 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!