Which code does in Julia script need to be written to make code from REPL running as script?

What need to be explicit mentioned (written out as code) in a Julia script which does not need to be mentioned while using Julia REPL? It seems that for example code which runs in the REPL taken 1:1 to a script does not work because of missing symbol names.

At least InteractiveUtils is automatically loaded in the REPL, so you need to put:

using InteractiveUtils

in scripts in order to be able to use things like versioninfo() which work automatically in the REPL.

2 Likes

In the REPL you have “soft scope”.

https://docs.julialang.org/en/v1/manual/variables-and-scoping/

That means this works in the REPL:

julia> x = 0
0

julia> for i in 1:10
           x += 1
       end

julia> x
10

However, this will not work:

$ julia -E "
x = 0
for i in 1:10
    x += 1
end
x
"
┌ Warning: Assignment to `x` in soft scope is ambiguous because a global variable by the same name exists: `x` will be treated as a new local. Disambiguate by using `local x` to suppress this warning or `global x` to assign to the existing global variable.
└ @ none:4
ERROR: UndefVarError: `x` not defined
Stacktrace:
 [1] top-level scope
   @ ./none:4

You need to add the global keyword.

$ julia -E "
x = 0
for i in 1:10
    global x += 1
end
x
"
10

My advice is to focus writing functions rather than scripts in Julia.

The following works.

julia> function foo()
           x = 0
           for i in 1:10
               x += 1
           end
           return x
       end
foo (generic function with 1 method)

julia> foo()
10

And also works outside the REPL.

$ julia -E "
function foo()
     x = 0
     for i in 1:10
         x += 1
     end
     return x
end
foo()
"
10
8 Likes

The development version of the documentation has additional information about this common confusion: Scope of Variables · The Julia Language

3 Likes

Isn’t there a preliminary script which needs to be imported into a script in its first line to provide what REPL comes with? Where does the REPL get its initialization from?