Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: Local inner functions



On 24 March 2011 10:38, René 'Necoro' Neumann <lists@xxxxxxxxx> wrote:
> Am 24.03.2011 02:41, schrieb Bart Schaefer:
>> On Wed, Mar 23, 2011 at 4:23 PM, René 'Necoro' Neumann
> <lists@xxxxxxxxx> wrote:
>>>
>>> foo ()
>>> {
>>>   bar () { }
>>> }
>>>
>>> Is there some way of making 'bar' to be local to 'foo'? Using the
>>> 'local' keyword does not work :).
>>
>> The short answer is "no."  And you can't make local aliases either.
>>
>> The slightly longer answer is that there are a couple of ways to fudge
>> it, of varying degrees of hackishness.
>
> Thanks for your answer. Instead of your 'always'-block, I tried
> trap 'unfunction bar' EXIT - but of course this is no good in case of
> name clashes :).
>
> So, if nothing like this really works (and local functions are not been
> to be implemented into zsh), I'll just use the $0_bar approach (wasn't
> aware of this), to at least reduce the chance of clashes.

If your function doesn't need to modify the parent environment in any
way, you can simply run it in a subshell:

function bar() { echo stuff }
function foo() {
 (
  function bar() { echo whatever }
  bar
 )
}
foo
bar

-- 
Mikael Magnusson



Messages sorted by: Reverse Date, Date, Thread, Author