type-conversionaspectspecman

What's the difference between to_string() and as_a(string) in specman?


In Specman I can convert a variable to a string using either:

x.to_string();

or

x.as_a(string);

Is there any difference between the two? If not, why does Specman provide both?


Solution

  • as_a() allows you to convert the expression to a specific type, not only string.

    These are few examples from the docs

    list_of_int.as_a(string)
    list_of_byte.as_a(string)
    string.as_a(list of int)
    string.as_a(list of byte)
    bool = string.as_a(bool) (Only TRUE and FALSE can be converted to Boolean; all other strings return an error)
    string = bool.as_a(string)
    enum = string.as_a(enum)
    string = enum.as_a(string) 
    

    UPDATE:

    using as_a(string) and to_string() not always gives the same results.

    var s: string;
    s = "hello";
    var lint: list of int;
    lint = s.as_a(list of int);
    print lint;
    print lint.as_a(string);
    print lint.to_string();
    

    This will print something like this:

    lint =
      104
      101
      108
      108
      111
    lint.as_a(string) = "hello"
    list.to_string() = "104 101 108 108 111"
    

    This is because to_string will run on each element of the list and then the list will be concatenated with spaces, as_a will however convert integers to characters and concatenate them, giving you the hello word.