# Replacing Variable Name with a String in a Julia Macro

**URL:** <https://discourse.julialang.org/t/replacing-variable-name-with-a-string-in-a-julia-macro/105579>\
**Category:** General Usage\
**Tags:** macros\
**Created:** [October 30, 2023, 4:29pm UTC](https://discourse.julialang.org/t/replacing-variable-name-with-a-string-in-a-julia-macro/105579 "2023-10-30T16:29:24Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Akhil\_Akkapelli](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/akhil_akkapelli/32/202792_2.png) [@Akhil\_Akkapelli](https://discourse.julialang.org/u/Akhil_Akkapelli)\
**Post date:** [October 30, 2023, 4:29pm UTC](https://discourse.julialang.org/t/replacing-variable-name-with-a-string-in-a-julia-macro/105579/1 "2023-10-30T16:29:24Z")

</div>

I’m working on a project where I need to create a macro in Julia that takes a Julia code expression, a variable name, and a string as input and returns the same expression with the specified variable name replaced by the given string. It’s important that the macro respects variable scoping in Julia.

For example, if I have the following expression:

```julia
x = 42
expr = :(2 * x + 3)

```

And I call the macro with the variable name x and the replacement string “y”, like this:

```julia
@my_macro expr x "y"

```

I want to get the modified expression:

```julia
:(2 * y + 3)

```

I’ve been trying to implement this macro, but I’m having trouble dealing with variable scoping and ensuring that the replacement only occurs for the specified variable.

I’d appreciate any guidance or assistance in implementing this macro correctly. If anyone has any insights, code snippets, or advice on how to achieve this in Julia, please share them with me.

---

<div class="post-metadata">

**Author:** ![savq](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/savq/32/22063_2.png) [@savq](https://discourse.julialang.org/u/savq)\
**Post date:** [October 30, 2023, 5:07pm UTC](https://discourse.julialang.org/t/replacing-variable-name-with-a-string-in-a-julia-macro/105579/2 "2023-10-30T17:07:19Z")

</div>

Hi @Akhil_Akkapelli, usually it’s easier to help you if you provide the code you’ve tried.

Before writing a macro, I usually write a function from `Expr` to `Expr` and then write the macro to wrap that function. In this case I believe the following would work:

```julia-repl
julia> begin
           replace_identifier(id::Symbol, old, new) = id == old ? new : id
           replace_identifier(expr::Expr, old, new) = Expr(expr.head, replace_identifier.(expr.args, old, new)...)
           replace_identifier(token, _, _) = token # ignore non-symbol tokens
       end
replace_identifier (generic function with 3 methods)

julia> replace_identifier(:(2 * x + 3), :x, :y)
:(2y + 3)

```
