[英]Why does using a comma concatenate strings in PowerShell?
I have encountered a PowerShell behavior I don't understand.我遇到了我不明白的 PowerShell 行为。 A comma between strings concatenates them and inserts a space in between, eg:
字符串之间的逗号连接它们并在它们之间插入一个空格,例如:
PS H:\> [string]$result = "a","b"
PS H:\> $result # a string with 3 characters
a b
If the result is interpeted as an array, then using a comma separates the elements of the array, eg:如果结果以数组的形式插入,则使用逗号分隔数组的元素,例如:
PS H:\> [array]$result = "a","b"
PS H:\> $result # an array with 2 elements
a
b
I have tried searching for an explanation of this behavior, but I don't really understand what to search for.我曾尝试寻找对这种行为的解释,但我真的不明白要搜索什么。 In the documentation about the
comma operator
, I see that it is used to initialize arrays, but I have not found an explanation for the "string concatenation" (which, I suspect, may not be the correct term to use here).在有关
comma operator
的文档中,我看到它用于初始化 arrays,但我还没有找到“字符串连接”的解释(我怀疑,这可能不是在这里使用的正确术语)。
Indeed: ,
is the array constructor operator .确实:
,
是数组构造器操作符。
Since your variable is a scalar - a single [string]
instance - PowerShell implicitly stringifies your array (converts it to a string).由于您的变量是标量- 单个
[string]
实例 - PowerShell 隐式字符串化您的数组(将其转换为字符串)。
PowerShell stringifies arrays by joining the (stringified) elements of the array with a space character as the separator by default. PowerShell 默认情况下,通过使用空格字符作为分隔符连接数组的(字符串化)元素,对arrays 进行字符串化。
You may set a different separator via the $OFS
preference variable , but that is rarely done in practice.您可以通过
$OFS
首选项变量设置不同的分隔符,但在实践中很少这样做。 [1] [1]
You can observe this behavior in the context of string interpolation :您可以在字符串插值的上下文中观察此行为:
PS> "$( "a","b" )"
a b
[1] As zett42 points out, an easier way to specify a different separator is to use the -join
operator ; [1] 正如zett42指出的那样,指定不同分隔符的更简单方法是使用
-join
运算符; eg,例如,
"a", "b" -join '@'
yields 'a@b'
. "a", "b" -join '@'
产生'a@b'
。
By contrast, setting $OFS
without resetting it afterwards can cause later commands that expect it to be at its default to malfunction;相比之下,设置
$OFS
而不在之后重新设置它可能会导致以后希望它处于默认状态的命令出现故障; with -join
you get explicit control.与
-join
你得到明确的控制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.