Reputation: 53
I would like to know if it is possible to call a method from an object without passing the self argument.
As an example, I have a package:
package MyPackage;
sub new {
my $class = shift;
return bless {}, $class;
}
sub test {
print("called(" . join(', ', @_) . ")\n");
}
From a script, I call the constructor and then the test
method:
my $obj = MyPackage->new();
$obj->test("str");
giving me the following output:
called(MyPackage=HASH(0x55b05d481f48), str)
Is there any way (even if it's not a best practice or use some "arcane"
features of the language) to call the test
method using only the reference
$obj
without having the "self"-parameter passed implicitly.
In a word, is it possible to do something like this:
$objXXXXtest("str");
with XXXX
the hypothetical construct and get called(str)
as output?
Upvotes: 3
Views: 859
Reputation: 118595
It's a little unorthodox, but UNIVERSAL::can
returns a code reference that you could call without the referent.
$obj->can("test")->("str");
Upvotes: 8
Reputation: 943100
You would just call the function directly, and not as a method of an object:
myPackage::test("str");
Upvotes: 0