Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass arguments to function referenced by variable

I have a function 'foo' and a variable '$foo' referencing it.

function foo
{
    param($value)
    $value + 5
}

$foo = foo
$foo

I can call $foo without args, but how can I pass parameters? This does not work:

$foo 5
$foo(5)

Actually the goal is to write such code:

function bar {
  param($callback)
  $callback 5
}

bar(foo)
like image 241
alex2k8 Avatar asked Mar 26 '09 13:03

alex2k8


2 Answers

The problem is when you do

$foo = foo

You put the result of the function in the variable $foo, not the function itself !

Try this :

$foo = get-content Function:\foo

And call it like this

& $foo 5

Hope it helps !

like image 80
Cédric Rup Avatar answered Nov 15 '22 07:11

Cédric Rup


Use a script block.

# f.ps1

$foo = 
{
    param($value)
    $value + 5
}

function bar 
{
  param($callback)
  & $callback 5
}

bar($foo)

Running it:

> ./f.ps1
10
like image 27
dan-gph Avatar answered Nov 15 '22 07:11

dan-gph