Stop perl overloading or print memory “address” of

2019-06-24 12:10发布

问题:

I have a class I created that overloads the "" operator to print out a nice stringified form of the object that is user-readable.

But now, I'd like to actually get the memory address such as:

Some_class=HASH(0xb0aff98)

which is what I would have normally done by using print "$some_object" if I had not already overridden the "" operator.

Is there someway to bypass the overridden method or, failing that, just get the memory address of this object?

回答1:

Use overload::StrVal($o).

use overload '""' => sub { "Hello, World!" };
my $o = bless({});
print($o, "\n");                     # Hello, World!
print(overload::StrVal($o), "\n");   # main=HASH(0x62d038)


回答2:

Two options:

  1. Use overload::StrVal

    Public Functions

    Package overload.pm provides the following public functions:

    • overload::StrVal(arg)

      Gives the string value of arg as in the absence of stringify overloading. If you are using this to get the address of a reference (useful for checking if two references point to the same thing) then you may be better off using Scalar::Util::refaddr() , which is faster.

  2. Use Scalar::Util::refaddr()

    $addr = refaddr( $ref )

    If $ref is reference the internal memory address of the referenced value is returned as a plain integer. Otherwise undef is returned.

       1.    $addr = refaddr "string";           # undef
       2.    $addr = refaddr \$var;              # eg 12345678
       3.    $addr = refaddr [];                 # eg 23456784
       4. 
       5.    $obj  = bless {}, "Foo";
       6.    $addr = refaddr $obj;               # eg 88123488