Zsh Mailing List Archive
Messages sorted by:
Reverse Date,
Date,
Thread,
Author
Re: anonymous function question
On Tue, Aug 23, 2022 at 5:37 AM Lawrence Velázquez <larryv@xxxxxxx> wrote:
>
> - Comment removal is performed during parsing. Thus, setting and
> unsetting INTERACTIVE_COMMENTS changes how parsing is done.
> - A complex command is parsed *in its entirety* before *any* of its
> commands are executed. Thus, a command within a complex command
> cannot affect how the rest of the complex command is parsed.
>
> Therefore, a complex command cannot enable or disable comments
> within itself. It can affect subsequent commands, though:
That's basically correct. Note that *all* options stay constant during
parsing, not just INTERACTIVE_COMMENTS. Also note that functions are
always parsed in their entirety and only once and aliases are expanded
during parsing. This often surprises people. Consider this script:
alias foo='echo 1'
function bar() {
foo
alias foo='echo 2'
}
bar
bar
bar
foo
This script prints "1" three times followed by "2". If you add
`functions bar` at the bottom to print the body of function bar, it'll
reveal what's going on:
bar () {
echo 1
alias foo='echo 2'
}
As you can see, the alias within the function has been expanded during parsing.
There are several more options (in addition to INTERACTIVE_COMMENTS
and ALIASES) that affect parsing: SH_GLOB, BRACE_EXPAND, etc.
# Set unusual options.
setopt no_brace_expand
function foo() {
# Set the usual options.
emulate -L zsh
print -- {1,2}
}
foo
This prints "{1,2}" rather than "1 2". Options set by a function
affect its execution but not parsing.
Another thing that can be surprising is that zcompile parses the whole
file all at once with the options and aliases that are active at the
time zcompile is invoked. This means that sourcing a file directly may
have a different effect from zcompiling and sourcing it afterwards.
>script.zsh <<\END
alias echo='echo 1'
echo 2
END
( source ./script.zsh )
zcompile ./script.zsh
( source ./script.zsh )
This prints "1 2" followed by "2".
This is one of the reasons I wouldn't recommend zcompiling zsh startup
files. There are other (and more important) reasons, too.
Roman.
Messages sorted by:
Reverse Date,
Date,
Thread,
Author