2

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?

martineau
  • 119,623
  • 25
  • 170
  • 301
Nathan Fellman
  • 122,701
  • 101
  • 260
  • 319

1 Answers1

2

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.

RaYell
  • 69,610
  • 20
  • 126
  • 152
  • so why is there a separate `to_string()` method? Is there any advantage to using it? – Nathan Fellman Sep 23 '09 at 09:26
  • This methods not always behave the same. Check my updated answer. – RaYell Sep 23 '09 at 10:02
  • Thanks! So if `lint` isn't a list or an integer they should be the same? For instance if it's an enum? – Nathan Fellman Sep 23 '09 at 11:56
  • In some cases (maybe even most of them) the result may be exactly the same. If you need type conversion you should use `as_a(string)`, if you want text representation of an object use `to_string()`. – RaYell Sep 23 '09 at 12:05
  • to_string() may also be over-written for structs and units, though I'm not sure if the overriding of to_string() affects as_a(string). – Ross Rogers Sep 23 '09 at 21:56