[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: assignment to a nameref that resolves to the temporary environment
From: |
Chet Ramey |
Subject: |
Re: assignment to a nameref that resolves to the temporary environment |
Date: |
Tue, 11 Dec 2018 15:37:08 -0500 |
User-agent: |
Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:52.0) Gecko/20100101 Thunderbird/52.9.1 |
On 12/9/18 1:28 AM, Grisha Levit wrote:
> When a nameref local to a higher function scope points to a variable in the
> temporary environment, that nameref (correctly, it seems) expands to the
> value
> of the target variable from the temporary environment. However, assignment
> to
> the nameref modifies the variable from the higher scope, bypassing the
> tempenv:
>
> $ a() { local -n ref=var; var=tmp b; echo $ref; }
> $ b() { ref=$ref; }
> $ var=foo; a
> tmp
Here's what happens when you execute `b'. The variable `var' is put into
the temporary environment with value `tmp'. The resolution for $ref looks
at the current environment, finds nothing, looks at the previous
environment (a), and finds a nameref with value `var'. It *restarts* the
lookup to resolve `var', finds it in the temporary environment, and expands
to `tmp'. So that's the value, and the assignment becomes `ref=tmp'.
The assignment code goes looking for `ref' and finds it in the previous
context as a nameref with value `var'. This is where the asymmetry occurs.
When performing an assignment, the shell starts at the context where the
nameref is found, rather than starting at the original context -- which in
this case, would have found the variable in b's temporary environment.
Do you think it's reasonable to have this restriction, given the nature of
bash's dynamic variable scoping, or should it restart the lookup from the
original variable context? You can get yourself into some pretty nasty
nameref loops if you go back to the original context.
Chet
--
``The lyf so short, the craft so long to lerne.'' - Chaucer
``Ars longa, vita brevis'' - Hippocrates
Chet Ramey, UTech, CWRU chet@case.edu http://tiswww.cwru.edu/~chet/