This suggests a pattern of invoking a Julia program from the command line and running it like a script, which is not a great development experience nor does it allow you to take advantage of precompilation. It’s probably better to start the Julia REPL and call a function to run a program. You can then modify the function in the REPL or use Revise.jl to reload your code file.
If I want a driver for my program, I usually make a special module for that case and invoke the code from the __init__
function, which usually just calls another function.
For example, I might make a HelloWorld.jl
with the following contents:
module HelloWorld
export helloworld
helloworld() = println("Hello World")
__init__() = helloworld()
end
I can then execute it as follows:
$ julia HelloWorld.jl
Hello World
I can also work with in the REPL as follows:
julia> module HelloWorld
export helloworld
helloworld() = println("Hello World")
__init__() = helloworld()
end
Hello World
Main.HelloWorld
julia> HelloWorld.helloworld()
Hello World
julia> using .HelloWorld
julia> helloworld()
Hello World
To start hacking on it, I might then do
julia> import .HelloWorld: helloworld
julia> helloworld() = "Hello Universe"
helloworld (generic function with 1 method)
julia> helloworld()
"Hello Universe"
julia> HelloWorld.helloworld()
"Hello Universe"
If I wanted to continue to edit the code in the file, I might then use Revise.includet("HelloWorld.jl")
in the REPL. I would then continue to modify the helloworld()
function until I met my basic prototyping threshold.
Eventually I would want to start formatting the code into a package. That usually would mean moving the file into ~/.julia/dev/HelloWorld/src/HelloWorld.jl
and creating ~/.julia/dev/HelloWorld/Project.toml
to give the module a unique UUID. PkgTemplates.jl can help you do this. You can then invoke your program via using HelloWorld
within the REPL or julia -e "using HelloWorld"
from any directory. You might complain about wanting your code to live somewhere else, and then we would need to go into details of the JULIA_DEPOT_PATH
environmental variable or using symlinks. It’s usually not worth it.
I know Julia looks like a scripting language, and it’s tempting to borrow workflow from your previous experience from scripting languages. However, Julia is really a compiled language, so that requires some changes in behavior otherwise you will spend a lot of time needlessly recompiling code while you are trying to work on it. That’s a formula for making everything slow. The easiest way to develop is to use the REPL which helps cache compilation for you. Eventually though we need form packages with unique identifiers so that Julia has some kind of compliable unit to cache.