如何拆分“如果"带有注释的多行条件 [英] How to split an "if" condition over multiline lines with comments

查看:27
本文介绍了如何拆分“如果"带有注释的多行条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在 PowerShell WITH 注释中将if"条件拆分为多行,请参见示例:

I cannot achieve to split an "if" condition over multiple lines in PowerShell WITH comments, see example:

If ( # Only do that when...
    $foo # foo
    -and $bar # AND bar
)
{
    Write-Host foobar
}

这会产生以下错误:

'if' 语句中的表达式后缺少结束 ')'.

Missing closing ')' after expression in 'if' statement.

添加 ` 字符不起作用:

Adding the ` character does not work:

If ( ` # Only do that when...
    $foo ` # foo
    -and $bar ` # AND bar
)
{
    Write-Host foobar
}

我得到一个:

表达式或语句中出现意外的标记 '` # foo'.

Unexpected token '` # foo' in expression or statement.

我发现的唯一方法是删除评论:

The only way I've found is to remove the comments:

If ( `
    $foo `
    -and $bar `
)
{
    Write-Host foobar
}

但我确信 PowerShell 提供了一种方法来做其他脚本语言可以做的事情:我似乎找不到它......

But I am sure PowerShell offers a way to do what others scripting languages can: I just seem cannot find it...

推荐答案

PowerShell 在识别到不完整的语句时会自动换行.对于比较操作,例如,如果您使用悬空运算符编写一行:

PowerShell automatically wraps lines when it recognizes an incomplete statement. For comparison operations this is the case if for instance you write a line with a dangling operator:

if ( # Only do that when...
    $foo -and  # foo AND
    $bar       # bar
)

否则 PowerShell 会将这两行解析为两个不同的语句(因为第一行本身就是一个有效的表达式),而第二行则因为它无效而失败.因此,您需要转义换行符.

Otherwise PowerShell will parse the two lines as two different statements (because the first line is a valid expression by itself) and fail on the second one because it's invalid. Thus you need to escape the linebreak.

但是,仅在行中的某处放置一个转义字符是行不通的,因为这将转义下一个字符并保持换行符不变.

However, just putting an escape character somewhere in the line won't work, because that will escape the next character and leave the linebreak untouched.

$foo ` # foo

将它放在带有(行)注释的行尾也不行,因为注释优先,将转义字符变成文字字符.

Putting it at the end of a line with a (line) comment also won't work, because the comment takes precedence, turning the escape character into a literal character.

$foo  # foo`

如果您想转义换行符,您需要将注释移至其他位置:

If you want to escape the linebreaks you need to either move the comment elsewhere:

if (
    # Only do that when foo AND bar
    $foo `
    -and $bar
)

或使用 @Chard 建议的块注释:

or use block comments as @Chard suggested:

if ( # Only do that when...
    $foo       <# foo #> `
    -and $bar  <# AND bar #>
)

但坦率地说,我的建议是将运算符移到上一行的末尾,避免转义换行符的所有麻烦.

But frankly, my recommendation is to move the operator to the end of the previous line and avoid all the hassle of escaping linebreaks.

这篇关于如何拆分“如果"带有注释的多行条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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