Newbie question on search path

Welcome!

Julia code typically uses more, smaller functions, with many functions living within a single file. You don’t have to do that, but I find that short functions are easier to describe, understand, and test. The fact that MATLAB only allows a single exported function per file, is, in my opinion, a significant downside to the language.

Since Julia code tends to have many functions, we need some way to organize them. The way we do that is with Modules. You can read about Modules in the manual here: https://docs.julialang.org/en/stable/manual/modules/

For example, you can make a module by creating a file called Foo.jl and adding the following:

module Foo

function f(x)
  println(x)
end

function g(x, y)
  x + y
end

end

To use the module you’ve just defined, you need to tell Julia where to look for it. See: https://docs.julialang.org/en/stable/manual/modules/#Module-file-paths-1 All you need to do is add the folder containing Foo.jl to your LOAD_PATH variable with push!(LOAD_PATH, "/path/to/folder"). Then you can load your module with:

using Foo

Foo.f(1.0)

Note that the name of the module matches the name of the file: module Foo is in Foo.jl. The filename matters, and when you do using Foo Julia will expect to find Foo.jl or Foo/src/Foo.jl somewhere in LOAD_PATH.

If you want to call the f function without the Foo. prefix, you can modify your module:

module Foo

export f

function f(x)
  println(x)
end

function g(x, y)
  x + y
end

end

Then you can do:

using Foo
f(1.0)

If you don’t want to do the push!(LOAD_PATH, ...) every time you start Julia, you can either set the JULIA_LOAD_PATH environment variable, or you can just add that push! statement to your ~/.juliarc.jl file. For more info see: https://docs.julialang.org/en/stable/manual/getting-started/#Getting-Started-1

If your module starts to get too big to comfortably remain in a single file, you can split it up into files however you like. See: https://docs.julialang.org/en/stable/manual/modules/#Modules-and-files-1

Finally, as your code matures to the point where you’d like to share it with other people, you can turn it into a package, which other people will be able to install with Pkg.add() or Pkg.clone(). For more info see https://docs.julialang.org/en/stable/manual/packages/

7 Likes