Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is Perl's default object-to-string conversion defined?

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.

like image 212
Johannes Ernst Avatar asked Jan 03 '23 11:01

Johannes Ernst


2 Answers

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);
like image 198
ikegami Avatar answered Jan 14 '23 13:01

ikegami


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)

like image 24
Johannes Ernst Avatar answered Jan 14 '23 14:01

Johannes Ernst