I have encountered a strange issue while migrating code from Julia 1.10 to Julia 1.12.3. It seems like a variable assignment within a function is not being reflected correctly in the caller’s scope, or I am fundamentally misunderstanding a change in the recent version.
Here is a minimal working example:
str = "[1 232.4;\n 2 40;\n 2 40];"
write("my_file.txt", str)
function readFile(str::String)
flag = false
for line in eachline("my_file.txt")
if !flag && occursin("[", line)
flag = true
println("Flag value after first change: ", flag)
end
if flag
flag = parseLine(line, flag, "[", "]")
println("Flag returned from parseLine: ", flag)
end
end
end
function parseLine(line::String, flag::Bool, start::String, last::String)
if occursin(start, line)
line = split(line, start)[end]
end
if occursin(last, line)
flag = false
println("Flag updated inside parseLine: ", flag)
end
return flag
end
readFile(str)
The problematic output:
Flag value after first change: true
Flag returned from parseLine: true
Flag returned from parseLine: true
Flag updated inside parseLine: false
Flag returned from parseLine: true <-- Why is this true?
The last line indicates that even though parseLine explicitly returned false, the flag variable in the readFile function remains true.
Two strange observations:
- Adding an
elseblock fixes it: If I modifyparseLineto explicitly setflag = truein anelsebranch, the output is correct (the flag becomesfalsein the caller scope).
function parseLine(line::String, flag::Bool, start::String, last::String)
if occursin(start, line)
line = split(line, start)[end]
end
if occursin(last, line)
flag = false
println("Flag updated inside parseLine: ", flag)
else
flag = true
end
return flag
end
- Commenting out the
splitlogic:
if occursin(start, line)
line = split(line, start)[end]
end
also fixes it.
I am certain this logic worked in Julia 1.10. Has there been a change in how local bindings or string manipulations (like split) interact with function returns in Julia 1.12?
Any help or explanation would be greatly appreciated!