String questions

chr="ppp"
pppfile="c:/Users/Dsektop/"*chr*".csv"

I want to use chr to generate the “pppfile”.I tried like the following

julia> ($chr)file="c:/Users/Dsektop/"*chr*".csv"
ERROR: syntax: extra token "file" after end of expression
Stacktrace:
 [1] top-level scope
   @ none:1

But it failed.How do I use chr to generate pppfile(just the name)?Thanks

You would need to use eval, but that is probably not the right path. If you have many files for which you need to associate names, how about using a dict:

julia> files = Dict{String,String}()
Dict{String, String}()

julia> files[chr*"file"] = "c:/Users/"*chr*".csv"
"c:/Users/ppp.csv"

julia> files["pppfile"]
"c:/Users/ppp.csv"
6 Likes

Using eval here seems to require a lot of string escaping:

file = "c:/Users/Desktop/" * chr * ".csv"
eval(Meta.parse("$(chr)file = \"\$(file)\""))

Warning: using eval is not recommended by Julia’s experts and alternatives like @lmiq’s nice solution are preferable.

3 Likes

The simple answer is “Don’t do this”. Dynamically generating variable names is a bad idea, and you should instead use a collection datatype, probably Dict, as @lmiq suggested.

There are also better and safer ways of building the file path. For example, you can use normpath, which fixes your path to be correct for the current platform:

julia> normpath("c:/Users/Desktop", chr*".csv")
"c:\\Users\\Desktop\\ppp.csv"

It sets the correct path separator, and also removes .. etc:

julia> normpath("c:/Users/../Desktop", chr*".csv")
"c:\\Desktop\\ppp.csv"

1.8.0> normpath("C:/", "Users", "Desktop", chr*".csv")
"C:\\Users\\Desktop\\ppp.csv"
5 Likes