Need to save the module hierarchy into a string using $sformatf(%m) in system verilog

In reply to yashg3:

Your issue has nothing to do with $display versus $sformat. Because you put a string declaration inside an unnamed begin/end block, some tools automatically generate a name for you and included as part of the %m format.

module top;
   initial begin
     string s;
     $display("Inside 1st %m");
   end
   initial begin
     string s;
     $display("Inside 2nd %m");
   end
endmodule

Now you have two variables named S local to each block. Move the string declaration outside the begin/and block in your example to fix the problem.