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

Re: Function-scoped parameters?



On Wed, 23 Feb 2011, Benjamin R. Haskell wrote:

This doesn't work, probably unsurprisingly. But is there a way to accomplish it?

function () {
   emulate -L zsh
   local x=asdf
   trap 'echo x is ${x:-unset}' EXIT
}

The use case is that I want to assign a local parameter 'temp' to be set to the name of a temporary file. If anything goes wrong in the function, I'd like that temporary file to be removed, but I don't want 'temp' to leak out of the function scope.

e.g.:
dosomething () {
   emulate -L zsh
   local temp=$(mktemp)
   setopt err_return
   trap '(( $+temp )) && rm $temp' EXIT
   # ...
}


Hmm. The following seems to do what I want, but seems kludgy and zsh-specific (which might be fine, but this seems like something other shells should be able to do). (Main problem might be that I tend to code as if I'm using Perl even when I'm not.)

dosomething () {
    emulate -L zsh
    setopt err_return
    local temp=$(mktemp)
    function () {
        trap '(( $+temp )) && rm $temp' EXIT
        # ... do stuff ...
    }
    # at this point, $temp has always been cleaned up (error or no)
}
dosomething blah blah
# at this point, $temp is not leaked

--
Best,
Ben



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