Writing to file removes escape char

I have this string s

julia> s = "abc.\$foo"

julia> s
"abc.\$foo"

When I write it to file, this happens:

julia> open("moo.jl", "w") do io
       write(io, s)
       end
8

And in moo.jl I have:

abc.$foo

So I get $foo instead of \$foo. Is this expected? If so, what is the way to preserve the escape char?

Yes this is expected.The \$ causes a dollar sign to be inserted into the string rather than doing the normal string replacement.

If you want to write abc.\$foo to a file you would need to declare the string like “abc.\\\$foo”. Or maybe you could do something like string(“abc.”, “\\”, “$”, “foo”) if that would be easier to read. You need the double slash to avoid escaping the end quote…

4 Likes

Another way of putting what @pixel27 said is that writing to the file didn’t change anything. Your string never contained a \ character:

julia> s = "abc.\$foo"
"abc.\$foo"

julia> collect(s)
8-element Array{Char,1}:
 'a'
 'b'
 'c'
 '.'
 '$'
 'f'
 'o'
 'o'

Julia is printing a \ because it’s trying to helpfully show you what you would need to input to re-create the string you have. You need the \$ to get the literal $ in the resulting string.

2 Likes

Yes, I see, makes sense! Thanks!

And to show the same point in a different way:

julia> s = "abc.\$foo";
"abc.\$foo"

julia> print(s)
abc.$foo
1 Like

You can also use a raw string literal if you don’t want characters inside it to be escaped:

julia> collect(raw"abc.\$foo")
9-element Array{Char,1}:
 'a'
 'b'
 'c'
 '.'
 '\\'
 '$'
 'f'
 'o'
 'o'
3 Likes

Thanks - yes, that makes total sense, of course the \$ simply escapes the interpolation. I was trapped in between the JS and JL worlds where I was generating JL files which contain Julia functions which generate JS code which contains $ variables and at some point my brain turned off. :slight_smile: