tags:

views:

97

answers:

3

New to OOP with Perl, and just had a quick question. I have this function in a class:

sub Print{
    my $text = shift;
    print "my text is", $text;
}

I try to print the text out, by doing this:

my $object = ObjectName->new();
$object->Print("Print this text")

It prints this:

my text isObjectName=SCALAR(0x1289df0)

My question is, why does it do this and how can I get it to simply print the text I pass as an argument?

+10  A: 

This:

$object->Print("Print this text");

Is (mostly) equivalent to this:

ObjectName::Print($object, "Print this text");

The first argument to any method is $self, which is a blessed reference and looks all ugly when you print it like that. You want to print the second argument. See perlboot and perltoot for more info.

Chris Lutz
I was reading perlboot, just checked over perltoot, and can't seem to find a solution. I'll reread both and see if I can figure out what im doing wrong.
Codygman
This section ("Inheriting the Constructor" http://perldoc.perl.org/perlboot.html#Inheriting-the-constructor) deals specifically with what you want.
Chris Lutz
Thanks Chris, I was messing around with "ref" trying to get that to work. I'll check out that section now!
Codygman
+11  A: 

Change your method to:

sub Print{
    my ($self, $text) = @_;
    print "my text is", $text;
}

When you call a method on an object in Perl (i.e. when you go $object->Print(...), in this case), the first argument passed to the method is the object itself.

asjo
The other answer had great information in it, but i'm going to pick yours for something that worked right away :)
Codygman
+6  A: 

When you have these sorts of problems, check your argument list to see what's going on:

use Data::Dumper;

sub Print {
     print Dumper( \@_ ), "\n";
     ...;
}

You should almost never suspect Perl as the source of a bug, at least until you've eliminated almost everything else.

brian d foy
Thanks for the debugging info, i'll definitely keep this in mind in the future!
Codygman