Scope of variables inside functions, for loops, and if statments

Does your code even need am and dt to be defined in the outer scope?
This should work fine:

function read_amdt(dir)
    wd = pwd()
    let am, dt
        try
            cd(dir)
            nii_files = glob("*nii",dir)
            for file in nii_files
                println(file)
                if occursin(r"/[Dd][Tt].*nii",file)
                    println("reading $file")
                    dt = niread(file)
                    println(typeof(dt))
                end
                if occursin(r"/[Aa][Mm].*nii",file)
                    println("reading $file")
                    am = niread(file)
                    println(typeof(am))
                end
                println(typeof(dt))
                println(typeof(am))
            end
        finally
            cd(wd)
        end
        return am, dt
    end
end
1 Like