Glob with variable names

I am trying out some pattern matching with glob. When I try it using subfolders it works if the subfolder is hardcoded, but not when the subfolder is a variable.

The purpose of the code is to delete files older than a set length of time. I have posted the code and the output of f1 should agree to the output of f2 but it does not. Any suggestions or is this a bug?

using Revise
using Glob

# function to delete old files
function datfilepurge(purgatoryfolder::String, retain::Period)
    datfiles = readdir(glob"$purgatoryfolder/*.dat")
    for (i, file) in enumerate(datfiles)
        age = now() - ctime(joinpath(purgatoryfolder, file))
        if age > retain
            rm(joinpath(purgatoryfolder, file))
        end
    end
end

purgatoryfolder = "purgatorytest"

# setup a subfolder and put some files into it
rm(purgatoryfolder, force = true, recursive = true)
mkdir(purgatoryfolder)
write(joinpath(purgatoryfolder, "file1.dat"), "file1 text"); sleep(1)
write(joinpath(purgatoryfolder, "file2.dat"), "file2 text"); sleep(1)
write(joinpath(purgatoryfolder, "file3.dat"), "file3 text"); sleep(1)
write(joinpath(purgatoryfolder, "file4.dat"), "file4 text"); sleep(1)
write(joinpath(purgatoryfolder, "file5.dat"), "file5 text"); sleep(1)

t = "$purgatoryfolder/*.dat"  # prove that this is a valid construct
f1 = readdir(glob"$purgatoryfolder/*.dat")  # This returns an emptyp String vector
f2 = readdir(glob"purgatorytest/*.dat")     # This returns the files in the folder
@show(t, f1, f2)

retain = Second(3)              # The length of time to retain the files for
datfilepurge(purgatoryfolder, retain)  # Remove old files

f3 = readdir(glob"$purgatoryfolder/*.dat")
f4 = readdir(glob"purgatorytest/*.dat")
@show(f3, f4)
nothing

with the following output

t = "purgatorytest/*.dat"
f1 = String[]
f2 = ["purgatorytest\\file1.dat", "purgatorytest\\file2.dat", "purgatorytest\\file3.dat", "purgatorytest\\file4.dat", "purgatorytest\\file5.dat"]
f3 = String[]
f4 = ["purgatorytest\\file1.dat", "purgatorytest\\file2.dat", "purgatorytest\\file3.dat", "purgatorytest\\file4.dat", "purgatorytest\\file5.dat"]
1 Like

$ interpolation doesn’t work (by default) in string macros like glob"..." or raw"...." or r"....": it is treated as a literal dollar sign. Try Glob.GlobMatch("$purgatoryfolder/*.dat") instead.

You can also do readdir(glob"*.dat", purgatoryfolder) or glob("*.dat", purgatoryfolder).

2 Likes