try在终端和VSCode运行结果不一样

julia> computername = "s"
"s"

julia> try
           computername = ENV["COMPUTERNAME"]
       catch
           computername = ENV["HOSTNAME"]
       end
"DESKTOP-FDIN0I7"

julia> computername
"DESKTOP-FDIN0I7"

这是终端运行的。(不过“软作用域”不是不会遮蔽全局变量吗?为啥它和for都能改全局变量?)

但是把这段代码搬到VSCode中运行有点不同:

┌ Warning: Assignment to `computername` in soft scope is ambiguous because a global variable by the same name exists: `computername` will be treated as a new local. Disambiguate by using `local computername` to suppress this warning or `global computername` to assign to the existing global variable.
└ @ d:\Documents\Julia\20221027VSCode远程调用Julia测试\test.jl:4
┌ Warning: Assignment to `computername` in soft scope is ambiguous because a global variable by the same name exists: `computername` will be treated as a new local. Disambiguate by using `local computername` to suppress this warning or `global computername` to assign to the existing global variable.
└ @ d:\Documents\Julia\20221027VSCode远程调用Julia测试\test.jl:6
s

我只有在前面加上global才能达到我想要的结果。怎么这里又突然遮蔽不了全局变量呢?

相反,for无论在终端还是VSCode里面,都是可以改外面同名变量的(话说这还是“软作用域”吗?)。

通过 REPL执行代码 和在shell终端直接执行 julia code.jl来运行代码时会面临不一样的作用域。以下是文档中关于soft scope的解释:

  1. **软作用域:**如果 x 并非已经是局部变量,并且所有包含 此次赋值的作用域结构是软作用域(循环、try/catch 块、或者 struct 块), 最后行为取决于全局变量 x 是否被定义:
  • 如果全局变量 x未定义,最终此次赋值会在该作用域创建一个名为 x 的新局部变量 ;
  • 如果全局变量 x已定义,此次赋值会被认为是有歧义的:
    • 非交互的上下文(文件、eval)中,会打印一个有歧义警告,同时创建一个新局部变量;
    • 交互的上下文(REPL, notebooks)中,会向全局变量 x 赋值。

更多具体内容可参考文档: 局部作用域 (julialang.org)

1 个赞