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

Hi,
In the below code, I would like to get the hierarchy into a string m1/m2. only upto module instance. But I am getting some thing extra like “unnamed$$_0” at the end… Can we get the module hierarchy from $sformatf(%m) similar to $display(%m) to store the hierarchy into a string…?

module top;
   buff b0 (.buf_in(1'b0), .buf_out());
endmodule

module buff (
   input  buf_in,
   output buf_out
);
   wire  a;
   inv i0 (.in(buf_in), .out(a      ));
   inv i1 (.in(a     ), .out(buf_out));
   initial $display("Inside hierarchy %m");
endmodule

module inv (
   input  in,
   output out
);
   assign out = ~in;
   initial
     begin
       string m1,m2 ;
       m1 = $sformatf("%m");
       $sformat(m2,"%m");
       $display("string m1 is %s",m1);
       $display("string m2 is %s",m2);
     end
endmodule

Output :
Inside hierarchy top.b0
string m1 is top.b0.i0.unnamed$$_0
string m2 is top.b0.i0.unnamed$$_0
string m1 is top.b0.i1.unnamed$$_0
string m2 is top.b0.i1.unnamed$$_0

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.

In reply to dave_59:

Thank you Dave. String declaration outside the begin/end block has solved the issue.