If I print a reference to a blessed object in Perl, I get something like this:
Foo::Bar=HASH(0x0123456789ab)
Where is that code defined? The first part is ref($obj)
, but where does the HASH hex value come from?
I'm attempting to write a to_string
overloaded operator for objects that have an optional name
attribute. If the name
is provided, I'd like it to print
Foo::Bar(name=joe)
and fall back to the default Perl string if not name
is undefined. So I either have to be able to invoke Perl's conversion code from my code, or write the equivalent myself, hence my question.
I don't believe the format is documented, but it's unlikely to change. It's equivalent to
use Scalar::Util qw( blessed refaddr reftype );
my $pkg = blessed($ref);
my $str = sprintf("%s%s(0x%x)",
( defined($pkg) ? "$pkg=" : "" ),
reftype($ref),
refaddr($ref),
);
You can use blessed
, reftype
and refaddr
if you want the components of Perl's stringification of a reference, but the following is the best way to obtain Perl's stringification of a reference:
use overload qw( );
my $str = overload::StrVal($ref);
Never mind, of course the minute after I post this, I find the answer:
overload::StrVal($o)
(see also Stop perl overloading or print memory "address" of reference)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With