-
Notifications
You must be signed in to change notification settings - Fork 8.1k
Closed
Labels
Issue-Questionideally support can be provided via other mechanisms, but sometimes folks do open an issue to get aideally support can be provided via other mechanisms, but sometimes folks do open an issue to get aResolution-AnsweredThe question is answered.The question is answered.WG-Languageparser, language semanticsparser, language semantics
Description
Scriptblocks seem to be PowerShell's analog to other languages' anonymous functions. I'm finding scriptblock's role as anonymous anonymous functions critical to writing maintainable code. Unlike anonymous functions in C#, for example, how a scriptblock is invoked seems to affect its behavior. The method of invocation seems affect behavior in (at least) the following ways:
- Whether variable assignments in the scriptblock have side-effects in the definition's scope.
- Whether
param()can be used.
Consider the following code:
New-Module m {
$v = 'c'
function f {
param($sb)
% $sb
}
function g {
param($sb)
& $sb -p1 'p1 is bound'
}
} | Out-Null
'--- & ---'
& {
$v = 'v is not modified by g'
g -sb {
param( $p1 )
process
{
$p1
$v = 'modified by g'
}
}
$v
}
'--- % ---'
& {
$v = 'v is not modified by f'
f -sb {
param( $p1 ) # <== these line are unused because % does not
$p1 # <== use parameter binding on this scriptblock
$v = 'v is modified by f'
}
$v
}which outputs
--- & ---
p1 is bound
v is not modified by g
--- % ---
v is modified by f
This seems to demonstrate the following:
- assignments in scriptblocks invoked using
&do not have side effects in the definition's scope - assignments in scriptblocks invoked using
%do have side effects in the definition's scope &supportsparam()
Judging from its help topic, % does not support using param().
The following table summarizes the behavior of % and & in these respects:
| Invocation Method | supports using param() |
variable assignment has side-effects |
|---|---|---|
| % | no | yes |
| & | yes | no |
Is there a way to invoke scriptblocks that supports using both param() and variable assignments with side effects?
Metadata
Metadata
Assignees
Labels
Issue-Questionideally support can be provided via other mechanisms, but sometimes folks do open an issue to get aideally support can be provided via other mechanisms, but sometimes folks do open an issue to get aResolution-AnsweredThe question is answered.The question is answered.WG-Languageparser, language semanticsparser, language semantics