I don’t understand variable scope in Julia. I wrote a function to read some data files. The program reads nifti (a format for storing medical images) files inside a for loop. The data read is then returned to the calling program.
Unfortunately, the data are of local scope inside the for loop (or the if statement), so I get an UndefVarError. I put global statements everywhere, and I still get the error.
Note: I recently upgraded from Julia 1.3.1-1 to 1.4.1-1. The program worked before the upgrade.
Here’s the code:
make_decmap.jl
using Images
using CSV
using NIfTI
using Glob
function read_amdt(dir)
wd=pwd();
cd(dir)
nii_files=glob("*nii",dir)
global dt
global am
for file in nii_files
println(file)
global dt
global am
if occursin(r"/[Dd][Tt].*nii",file)
println("reading $file")
global dt
dt=niread(file)
println(typeof(dt))
end
if occursin(r"/[Aa][Mm].*nii",file)
println("reading $file")
global am
am=niread(file)
println(typeof(am))
end
println(typeof(dt))
println(typeof(am))
end
cd(wd)
return am,dt
end
Note: nifti image files end .nii
Here are the commands I use in the REPL window, and julia’s output:
julia> dir="/mnt/data/PVP/philips/new_calib_test_data_temp_control_100518/asbUncor"
"/mnt/data/PVP/philips/new_calib_test_data_temp_control_100518/asbUncor"
julia> run(`ls $dir`)
AMu.nii DTu.nii EGu.nii EVu.nii FAu.nii test TRu.nii
Process(`ls /mnt/data/PVP/philips/new_calib_test_data_temp_control_100518/asbUncor`, ProcessExited(0))
julia> include("/mnt/data/julia/medical_imaging/make_decmap.jl")
make_decmap (generic function with 1 method)
julia> am,dt=read_amdt(dir)
/mnt/data/PVP/philips/new_calib_test_data_temp_control_100518/asbUncor/AMu.nii
reading /mnt/data/PVP/philips/new_calib_test_data_temp_control_100518/asbUncor/AMu.nii
NIVolume{Float32,3,Array{Int16,3}}
ERROR: UndefVarError: dt not defined
Stacktrace:
[1] read_amdt(::String) at /mnt/data/julia/medical_imaging/make_decmap.jl:27
[2] top-level scope at none:0