Freigeben über


Difference between $() and ()

 Today, I was writing some script to play around hash declaration. My line of script to declare hash was

 

MSH>$a = @{(‘foo’ + ‘bar’) = 5)}

MSH>$a.foobar

5

MSH>

Then, I tried

 

MSH>$a = @{$(‘foo’ + ‘bar’)=5}

MSH>$a.foobar

5

MSH>

 

That worked too. So, what’s the difference between () and $()

 

Answer is () is used only for expressions whereas $() is used for statement list. The above example works because ‘foo’ + ‘bar’ is treated as statement in $() case.

 

To clarify the point

 

MSH>$a = @{ $( $a=’foo’ ; $a += ‘bar’ ; $a) = 5}

MSH>$a.foobar

5

MSH>

 

The above will work fine. However,

 

MSH> $a = @{ ( $a=’foo’ ; $a += ‘bar’ ; $a) = 5}

 

will fail because parser expects an expression, but finds a statement list.

Comments