Jump to content

Runtime evaluation: Difference between revisions

no edit summary
m (removed use of pronouns in the task preamble.)
No edit summary
Line 1,041:
 
an actual application of this is shown in [[Simple database]].
 
=={{header|PowerShell}}==
Evaluate an expression:
<lang PowerShell>
$test2plus2 = '2 + 2 -eq 4'
Invoke-Expression $test2plus2
</lang>
{{Out}}
<pre>
True
</pre>
Evaluate a <code>[scriptblock]</code> (a statement or group of statements) with code surrounded by curly braces:
<lang PowerShell>
$say = {"Hello, world!"}
& $say
</lang>
{{Out}}
<pre>
Hello, world!
</pre>
Scriptblocks behave just as functions so they may have parameters:
<lang PowerShell>
$say = {param ([string]$Subject) "Hello, $Subject!"}
& $say -Subject "my friend"
</lang>
{{Out}}
<pre>
Hello, my friend!
</pre>
A slightly more complex example:
<lang PowerShell>
$say = {param ([string]$Exclamation, [string]$Subject) "$Exclamation, $Subject!"}
& $say -Exclamation "Goodbye" -Subject "cruel world"
</lang>
{{Out}}
<pre>
Goodbye, cruel world!
</pre>
To reverse the normal behaviour of a <code>[scriptblock]</code> use the '''GetNewClosure''' method. This makes the scriptblock self-contained or closed; ie, the variable will only be read when the scriptblock is initialised:
<lang PowerShell>
$title = "Dong Work For Yuda"
$scriptblock = {$title}
$closedScriptblock = $scriptblock.GetNewClosure()
 
& $scriptblock
& $closedScriptblock
</lang>
{{Out}}
<pre>
Dong Work For Yuda
Dong Work For Yuda
</pre>
Change the variable and execute the scriptblock, the closed version will not reflect the change:
<lang PowerShell>
$title = "Right Said Fred"
& $scriptblock
& $closedScriptblock
</lang>
{{Out}}
<pre>
Right Said Fred
Dong Work For Yuda
</pre>
 
=={{header|Python}}==
308

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.