When learning other languages there is often a difference between a class method and an object method.
I know that, in Perl, the class is weak. Is there also a difference between a class method and an object method?
I know the most often used class method may be the class's new
method. In Perl I can call all the methods with the package name, but not the package's object. Why is that?
Instance methods need a class instance and can access the instance through self . Class methods don't need a class instance. They can't access the instance ( self ) but they have access to the class itself via cls .
Object Basics The object is stored as a reference in a scalar variable. Because a scalar only contains a reference to the object, the same scalar can hold different objects in different classes. A class within Perl is a package that contains the corresponding methods required to create and manipulate objects.
Perl is an Objected Oriented, dynamic and interpreter based programming language. In object-oriented programming, we have three main aspects, which are, object, class, and methods. An object is a data type which can be specifically called as an instance of the class to which it belongs.
SUPER is used to call parent class's method from subclass. It means that along with method overriding, we can also call the method from subclass. The SUPER modifier can only be used for the method calls.
The perlobj
man page is helpful here:
When you call a method, the thing on the left side of the arrow is passed as the first argument to the method. That means when we call
Critter->new()
, thenew()
method receives the string"Critter"
as its first argument. When we call$fred->speak()
, the$fred
variable is passed as the first argument tospeak()
.
In other words, Perl doesn't make a sharp distinction between class methods and instance methods. They're differentiated by what gets passed as the first argument to the method, and if some methods don't actually happen to care about what gets passed as the first argument, then you can cheat and call them the "wrong" way.
Perl won't care. It usually doesn't.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With