Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop perl overloading or print memory "address" of reference

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?

like image 581
EMiller Avatar asked Dec 20 '22 10:12

EMiller


2 Answers

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)
like image 200
ikegami Avatar answered Mar 18 '23 06:03

ikegami


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
    
like image 45
Miller Avatar answered Mar 18 '23 07:03

Miller