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

Re: Local variables in sourced scripts



On Jun 29,  3:52pm, Andrej Borsenkow wrote:
} Subject: Local variables in sourced scripts
}
} Am I the only one who finds it useful? I'd really appreciate them in rc
} scripts - I always forget to unset temporary variables there and no fear
} to clobber some existing ones ...

You can't have it both ways.  In shell functions all variables are local
unless either explicitly declared global (with "typeset -g", and that only
works in 3.1.6+) or assigned-to without declaring.  

The problem is that you can't create any variables other than plain scalars
and simple arrays without declaring them.  If you make variables local to
rc files, then all declarations of integers, floats, associative arrays,
unique arrays ("typeset -U"), etc. must use -g, which will probably break
every nontrivial .zshrc on the planet (I know it'd screw mine up big time).

} Related question - I think, local functions were at least discussed
} sometimes. What is current status?

You can make a function with local scope, but only if it has the same
name as another function with global scope.  Like this:

    zmodload -i zsh/parameter
    function uselocalfn {
	local -A +h functions
	eval "function localfn {
	    echo this is the $1 local function
	}"
	localfn
    }

zagzig[104] localfn
zsh: command not found: localfn
zagzig[105] uselocalfn first
this is the first local function
zagzig[106] localfn
this is the first local function
zagzig[107] uselocalfn second
this is the second local function
zagzig[108] localfn
this is the first local function

This happens because the `functions' parameter has its value restored by
individual assignment to each associative array element.  Consequently,
only elements that existed before the local copy was created have their
old value restored; newly-created elements do not get erased.

Of course it's incredibly inefficient to redefine every global function
every time you want to use a single local function, so this probably is
in serious need of improvement.  Another side-effect is that when the
global value of $functions is restored, every autoloaded (aka undefined)
function turns into a defined function.  They still work as if they're
autoloaded, thanks to the magic of "autoload -X", but they no longer are
flagged as undefined.

-- 
Bart Schaefer                                 Brass Lantern Enterprises
http://www.well.com/user/barts              http://www.brasslantern.com

Zsh: http://www.zsh.org | PHPerl Project: http://phperl.sourceforge.net   



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