[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Help-bash] make function local
From: |
Dan Douglas |
Subject: |
Re: [Help-bash] make function local |
Date: |
Thu, 9 Apr 2015 00:05:45 -0500 |
On Tue, Apr 7, 2015 at 8:49 PM, Chet Ramey <address@hidden> wrote:
> Is there a particular problem you're trying to solve for which local
> functions would be the appropriate solution?
It's occasionally an optimization to eliminate some logic that only needs to be
performed on certain calls. A good (contrived) example might be a directory
traversal function that wants to enable nullglob and dotglob within its body.
# unoptimized
function dfs {
if [[ ! -v localopts ]]; then
typeset -a localopts
typeset opt
for opt in nullglob dotglob; do
shopt -q "$opt" || localopts+=("$opt")
done
shopt -s "address@hidden"
dfs "$@"
shopt -u "address@hidden"
return
fi
typeset file
for file; do
if [[ -d $file ]]; then
dfs "${file}/"*
elif [[ -f $file ]]; then
# do stuff
fi
done
}
# A tad better
function dfs {
typeset -a localopts
typeset opt
for opt in nullglob dotglob; do
shopt -q "$opt" || localopts+=("$opt”)
done
trap “trap RETURN; shopt -u ${localopts[*]}; $(typeset -fp dfs)” RETURN
function dfs {
typeset file
for file; do
if [[ -d $file ]]; then
dfs "${file}/"*
elif [[ -f $file ]]; then
# process the file
fi
done
}
dfs "$@"
}
I still vote "no" on this because:
1. It's doable with a 1-line RETURN trap as above.
2. If the semantics of nested functions were ever to change, the syntax
should be reserved for closure support.
3. Whoever ends up implementing this could have better spent their time
adding the sorely needed `shopt' option that localizes options so
that scripts
don't have to. ;-)
--
Dan Douglas