gpt4 book ai didi

bash - 理解词法范围——维基百科是否正确?

转载 作者:行者123 更新时间:2023-11-29 09:05:49 26 4
gpt4 key购买 nike

我一直在尝试理解词法范围(我不太相信 词法 这个词的使用,但那是另一个讨论)并且我查看了 Wikipedia's entry .

根据相当简单的 Bash 脚本示例

$ x=1 
$ function g () { echo $x ; x=2 ; }
$ function f () { local x=3 ; g ; }
$ f # does this print 1, or 3?
3
$ echo $x # does this print 1, or 2?
1

Bash 脚本的输出是 3, 1。但是,在我看来它应该是 3, 2,因为函数 g 打印 x 的(动态)值,然后设置 x = 2 的值。

我是否需要更正维基百科条目,或调整我的理解?

最佳答案

Bash 变量使用 dynamic scoping就像您提到的维基页面一样。

Examples of languages that use dynamic scoping include Logo, Emacs Lisp, and the shell languages bash, dash, and PowerShell.

Dynamic scoping is fairly easy to implement. To find an identifier's value, the program could traverse the runtime stack, checking each activation record (each function's stack frame) for a value for the identifier.

Bash 自己的 manual是这样说的:

The shell uses dynamic scoping to control a variable's visibilitywithin functions. With dynamic scoping, visible variables andtheir values are a result of the sequence of function calls thatcaused execution to reach the current function. The value of avariable that a function sees depends on its value within itscaller, if any, whether that caller is the "global" scope or anothershell function. This is also the value that a local variabledeclaration "shadows", and the value that is restored when thefunction returns.

For example, if a variable var is declared as local in functionfunc1, and func1 calls another function func2, references to var madefrom within func2 will resolve to the local variable var fromfunc1, shadowing any global variable named var.

有关如何使用它,请参阅 Bash: Passing variables by reference .

关于bash - 理解词法范围——维基百科是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48165818/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com