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

In package I have a method
package TEST; .......... sub new { my $class = shift; my $self = {@_}; bless $self, $class; return $self; } sub xxx { my $self = shift; my $par = shift; return $par; }
When I call in outside I do
my $obj = new TEST(); print $obj->xxx("hi")
If I do it inside package I have to put something for the first parameter and if I do it this way it works
print xxx("", "hi");
Is it a right way or do I violate something?

Replies are listed 'Best First'.
Re: Calling method inside and outside of package
by kcott (Archbishop) on Oct 28, 2010 at 18:29 UTC

    Inside the package you'd typically call it as: $self->xxx(...); - compare that format with $obj->xxx("hi") called from 'outside'.

    -- Ken

Re: Calling method inside and outside of package
by chromatic (Archbishop) on Oct 28, 2010 at 20:31 UTC
    Is it a right way or do I violate something?

    Always call methods as methods (with the explicit $invocant->method( @args ) syntax). You will break polymorphism otherwise by subverting method dispatch. (Perl 5 inherited this silly conflation of functions and methods from Python, but at least Moose and Perl 6 fix it.)

Re: Calling method inside and outside of package
by lyklev (Pilgrim) on Oct 28, 2010 at 19:50 UTC
    Your example works, because your routine xxx does nothing special. If you have a routine inside a package however, you will either want to do something with the data contained in your object, or you have a generic function that does not access your object's data.

    In the first case you would call the function as kcott mentioned, so as

    $obj -> xxx("hi");
    If you call the function from inside the package, you cannot access the data contained in the object, because you are passing an empty string instead of an object to the function.

    If you have a simple function (say, for adding two numbers), you can write a function like you normally would, so without getting the class name from the arguments.

    And never call a routine or program test --- there is probably another function or program with that name, which will take you a few hours to find out.