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

Re: How do you decide whether to make something a function or a script?



On Sat, Sep 8, 2018 at 6:22 PM, TJ Luoma <luomat@xxxxxxxxx> wrote:
>
> Why make any functions at all? Why not just make them all scripts?

The primary reason to make a program into a function is when it needs
to alter the state of the parent shell.  User-defined ZLE widgets are
the most obvious example, but there are other cases to want to make
persistent changes to the current shell.  (Yes, you can get some of
this with "source", but then you have to worry about parameter
scoping, etc.)

A secondary reason is efficiency.  Running a script requires forking a
subshell, examining the #! line to see if an external interpreter is
needed, and parsing the code, all before the script can begin doing
anything, and this happens every time it is run.  With functions,
there's no subshell, no guessing at the interpreter, and all the
parsing has been done up front (or is done only once on the first run,
in the case of an autoload).

Another reason is modularity.  A single file can define several
related functions, which leverages both of the first two advantages.

Yet another reason is to facilitate recursive programming.  A script
that runs itself creates many subshells, but a function that calls
itself only uses some recoverable memory space in the current shell.

There are more reasons, but most of them begin to be stylistic rather
than practical.  I'm sure others can add to my list.



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