Why should an expression be in parentheses for an array

When creating the second array in the files1 array, mathematical expressions should be placed in parentheses. Is the operator hierarchy applicable?

PS C:\src\powershell> Get-Content .\fr-btest2.ps1
$files1 = @(
, @(4, 1024)
, @(2*3, 4*5)
)

$files1
$files1.GetType()
$files1.Length
$files1.Count

'============'

$files2 = @(
, @(4, 1024)
, @((2*3), (4*5))
)

$files2
$files2.GetType()
$files2.Length
$files2.Count
PS C:\src\powershell> .\fr-btest2.ps1
Method invocation failed because [System.Object[]] does not contain a method named 'op_Multiply'.
At C:\src\powershell\fr-btest2.ps1:3 char:5
+ , @(2*3, 4*5)
+     ~~~~~~~~
    + CategoryInfo          : InvalidOperation: (op_Multiply:String) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

4
1024

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array
2
2
============
4
1024
6
20
True     True     Object[]                                 System.Array
2
2
+4
source share
1 answer

,(array construction operator) has a higher priority than* - seeGet-Help about_Operator_Precedence

Note. The following fragments do not use the array subexpression operator @(...), because there is no need to specify literals in the array - the array construction operator ,is sufficient.

Hence,

2*3, 4*5

analyzed as:

2 * (3, 4) * 5

and PowerShell doesn't know how to use an array in RHS *.

:
(2*3), (4*5) , 6, 20.


: PowerShell LHS *, : LHS () , (, ) RHS - , LHS *:

> (2,3) * 2  # equivalent of: 2, 3, 2, 3
2
3
2
3

, , , *, :

PowerShell - -replace -split - RHS.

, , , RHS:

> 'A barl and his money are soon parted.' -replace 'bar', 'foo'
A fool and his money are soon parted.

- -, , , , , , .

+5

Source: https://habr.com/ru/post/1672199/


All Articles