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?
- X-seq: zsh-users 23612
- From: Bart Schaefer <schaefer@xxxxxxxxxxxxxxxx>
- To: TJ Luoma <luomat@xxxxxxxxx>
- Subject: Re: How do you decide whether to make something a function or a script?
- Date: Sat, 8 Sep 2018 20:24:13 -0700
- Cc: Zsh-Users List <zsh-users@xxxxxxx>
- Dkim-signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=brasslantern-com.20150623.gappssmtp.com; s=20150623; h=mime-version:in-reply-to:references:from:date:message-id:subject:to :cc; bh=+E+lXeLZERhoHqnxIOi+vm+NxKFQXpZ5hSBIvJmGgtI=; b=y8UvRY39/SDb2RKQrvJ+GsGObdhb1AMNrQ1QYtoTZfnakBIYl3ZKMi4t4qwCu8FCk1 +4zc3uuqpi+KAvW7ttyqjbdTobQFo6KfpuDpa00asLW8HInfL+09fSXjUlEL8Jn78l7v nhlvrjv9oV3Zoabi8EEBzRS6regfl9l9SYFicR6BjjIkglibnBVZ+Cqmo4a6VMmVEfSP PlOwyhOZ8iffsXl0lff5oC0k+nQerAviOUfUMO6sn+PzSd/aMrsaM1s0K6CVgNS+LuiM GfBkpHPOcGf7N5NfGRjY76mAFNw/KmCjcKJi7m8glag3HsycPZD2RGtT33s6wqwedQ8j E93g==
- In-reply-to: <CADjGqHuK2oV3VzjHO0H5+FHJXC85HmysL9yPRjS-ESLhBcC3FA@mail.gmail.com>
- List-help: <mailto:zsh-users-help@zsh.org>
- List-id: Zsh Users List <zsh-users.zsh.org>
- List-post: <mailto:zsh-users@zsh.org>
- List-unsubscribe: <mailto:zsh-users-unsubscribe@zsh.org>
- Mailing-list: contact zsh-users-help@xxxxxxx; run by ezmlm
- References: <CADjGqHuK2oV3VzjHO0H5+FHJXC85HmysL9yPRjS-ESLhBcC3FA@mail.gmail.com>
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