Home > Net >  Use variable set in child function in Parent function
Use variable set in child function in Parent function

Time:03-25

Say I have a child function.

function hello {
$x= 1
$y = 2;    
}

function outerFunction {

hello

$z = $x   $y

}

Is it possible to somehow do this?

CodePudding user response:

You can use the Dot sourcing operator . to bring the variables defined in the scope of the hello function to the scope of outerFunction function:

function hello {
    $x = 1; $y = 2
}

function outerFunction {
    . hello
    $x   $y
}

outerFunction # => 3

You could also consider a different alternative depending on your use case, where the operator is not involved. For example:

function hello {
    1, 2
}

function outerFunction {
    $x, $y = hello
    $x   $y
}

outerFunction
  • Related