Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I know that the Math::BigInt objects can be printed with "print":
use Math::BigInt; print Math::BigInt->new("123"); # prints "123"
However, when I try to print an object that I create, it just prints something like the following: MyClass=HASH(0x9eff760) My question is, how do I tell it how to print objects of my class?

Replies are listed 'Best First'.
Re: How to make object printable
by tilly (Archbishop) on Mar 01, 2009 at 00:58 UTC
    Use overload to provide a stringification method for objects of your class. Then when you print them they will stringify using that method.
Re: How to make object printable
by Anonymous Monk on Mar 01, 2009 at 01:59 UTC
    Here's a very basic example to get you started:
    package ClassPrintable; use overload q{""} => sub { return shift->stringify() }; sub new { my ($class,$args) = @_; return bless($args,$class); } sub stringify { my $self = shift; my $ret = "{"; for (sort keys %$self){ $ret .= " $_ : ".$self->{$_}.","; } chop($ret) if (keys %$self); return "$ret".' }'; } package main; my $c = ClassPrintable->new({a =>1,b=>2,c=>3}); print $c;