bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: nameref and referenced variable scope, setting other attributes (was


From: Robert Elz
Subject: Re: nameref and referenced variable scope, setting other attributes (was "local -g" declaration references local var in enclosing scope)
Date: Thu, 14 Mar 2024 21:50:29 +0700

    Date:        Thu, 14 Mar 2024 09:53:37 -0400
    From:        Greg Wooledge <greg@wooledge.org>
    Message-ID:  <ZfMBYb38SoUUbtlZ@wooledge.org>

  | I don't quite understand what this is saying.

It was a weird attempt to explain the behaviour bel9w

  | Do the variables have different names, or the same name?

Depends which vars you mean but definitely not a nameref pointing
at itself.

Consider this script (/tmp/s)

f() {
        local v=1;
        printf 'in f v=%s\n' "$v"
        local -n n=v
        printf 'in f v=%s n=%s\n' "$v" "$n"
        g
        printf 'in f v=%s n=%s\n' "$v" "$n"
}

g() {
        local v=2
        printf 'in g v=%s\n' "$v"
        n=3
        printf 'in g v=%s n=%s\n' "$v" "$n"
}

f

Then running it (bash /tmp/s) produces

in f v=1
in f v=1 n=1
in g v=2
in g v=2 n=2
in f v=3 n=3

Some people do not understand how that works, believing
that n should always refer to the v in f, rather than the
v in g.

So 'the variables have the same names' are the v in f and v in g
(if those were different there would be no confusion), the nameref
var name is different.

kre

ps: I'm not sure how to explain what happens there either,
looks broken and useless to me.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]