finding instance of object

J

Jeff Thies

I have an object and I like to print the instance of the object;

my $object_name=new MyObj();
my $object_name2=new MyObj();

package MyObj;

sub new{
my $class = shift;
my $self = {};

....

sub printInstance{
my $self=shift;

print " I'd like to print $object_name, can I do that or do I need to
pass it in directly as a property?: my $object_name=new
MyObj('object_name');";

....

I don't remember reading about that in the perl OO guides, but I may
have missed it.

Cheers,
Jeff
 
G

Greg Bacon

: I have an object and I like to print the instance of the object;
: [...] I'd like to print $object_name, can I do that or do I need to
: pass it in directly as a property? [...]
:
: ...
:
: I don't remember reading about that in the perl OO guides, but I may
: have missed it.

If I understand your question, to call the printInstance method
(poorly named because the "hey, I operate on an instance" is
implicit -- just plain old print would be sufficient), you need
only invoke it as in

$obj->printInstance;

Behind the scenes, perl makes $obj the first parameter to the
method.

Hope this helps,
Greg
 
B

Brian Harnish

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

I have an object and I like to print the instance of the object;

my $object_name=new MyObj();
my $object_name2=new MyObj();

package MyObj;

sub new{
my $class = shift;
my $self = {};

...

sub printInstance{
my $self=shift;

print " I'd like to print $object_name, can I do that or do I need to
pass it in directly as a property?: my $object_name=new
MyObj('object_name');";

...

I don't remember reading about that in the perl OO guides, but I may
have missed it.

AFAIK, you can't do that. Take this for example:
my $object_name = new MyObj();
my $another_name = $object_name;

What should $another_name->printInstance() display? Or, what would you
expect to get from "$_->printInstance() for($object_name)"?

You could get the object class (package name) from the instance (would
print MyObj): "sub printInstance { print ref $_[0]; }"

Perhaps you could better outline the problem you're trying to solve with
this method. There may be a better way to solve that problem.

- Brian
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.2 (GNU/Linux)

iD8DBQE/WQDdiK/rA3tCpFYRAp8jAJsEe99D4fQ8lyyOLTqVp5EnASJm9gCgrQpa
puEb6RWRqfbRjeru2CzzeJY=
=UeCI
-----END PGP SIGNATURE-----
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,137
Messages
2,570,795
Members
47,342
Latest member
eixataze

Latest Threads

Top